Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding additional functionality to a PHP form

Tags:

forms

php

Given the code below when I select a value from my dropdown box [S, M, L] and hit submit I get one of the following outputs:

S is equal to
M is equal to
L is equal to

I would like the output to be along the lines of

S is equal to Small 
M is equal to Medium 
L is equal to Large

Can something be added to my code to accomplish this? Or do I need to take a different approach?

<form action="?" method="post">

<?php
$size = array();
$size[] = "";
$size[] = "S";
$size[] = "M";
$size[] = "L";
if(isset($_REQUEST['list'])){

    echo $size[(int)$_REQUEST['list']]." is equal to "."<br />"; 

}

echo '<select name="list">'."\n";
$count = 0;

foreach($size as $size){
    echo '<option value="'.$count.'">'.$size.'</option>'."\n";

    $count++;
}
echo '</select>';
?>

<input type="submit" value="submit" />
</form>


<form action="?" method="post">
like image 975
enfield Avatar asked Jun 10 '11 19:06

enfield


2 Answers

Why not use an associative array and then you don't have to mess around with ints or $counts?

<form action="?" method="post">

  <?php
    $sizes = array(
      "S" => "Small",
      "M" => "Medium",
      "L" => "Large"
    );

    if(isset($_REQUEST['list'])){
      echo "<p>" . $_REQUEST['list'] . " is equal to " . $sizes[$_REQUEST['list']] . "</p>"; 
    }
  ?>

  <select name="list">
    <option value="">Choose one</option>
    <?php
      foreach($sizes as $key => $val){
        echo "<option value='$key'>$key - $val</option>\n";
      }
    ?>
  </select>

  <input type="submit" value="submit" />
</form>

The output will look something like this:

S is equal to Small

+------------+-+
| Choose one |▼|
+------------+-+
| S - Small    |
| M - Medium   |
| L - Large    |
+--------------+
like image 116
Jordan Running Avatar answered Sep 27 '22 01:09

Jordan Running


With this solution you can reuse the original static array to populate the post echo. Also try to avoid using \n in your html instead use the semantic <br>.

<form action="?" method="post">

<?php
$size = array(""=>"","Small"=>"S","Medium"=>"M","Large"=>"L");

if(isset($_REQUEST['list'])){

    echo $size[$_REQUEST['list']]." is equal to ".$_REQUEST['list']."<br />"; 

}

echo "<select name='list'>";

foreach($size as $key=>$value){
    echo "<option value='$key'>$value</option>";

}
echo '</select>';
?>

<input type="submit" value="submit" />
</form>
like image 30
Laurence Burke Avatar answered Sep 27 '22 01:09

Laurence Burke