Create a Drop Down From Session Variables in PHP

Task: Create a drop down with minimum lines of code using the value in session variables.

Value in Session Variables:

$_SESSION[“totalvehicles”] = 3;

$_SESSION[“vehicleid_1”] = 22;
$_SESSION[“vehiclename_1”] = “2014 Toyota Crona”;
$_SESSION[“vehicleid_2”] = 33;
$_SESSION[“vehiclename_2”] = “2012 Honda Civic”;
$_SESSION[“vehicleid_3”] = 44;
$_SESSION[“vehiclename_3”] = “2009 Toyota Vitz”;

Solution (php code):

<select name=”primaryvehicle” id=”primaryvehicle” >
<?php

for ($i=1; $i<= $_SESSION[“totalvehicles”]; $i++)
echo “<option value='”.$_SESSION[‘vehicleid_’.$i].”‘>”.$_SESSION[‘vehiclename_’.$i].”</option>”;

?>

</select>

Result:

<select name=”primaryvehicle” id=”primaryvehicle” >
<option value=”22″>2014 Toyota Crona</option>
<option value=”33″>2012 Honda Civic</option>
<option value=”44″>2009 Toyota Vitz</option>
</select>