Php display promlem

Can any one tell me, why this code is not working properly ?



<?php

$employer = array('NA', 'PSU', 'Govt.', 'Others');


if($_POST)
{
	print_r($_POST);
}
?>

<form action="" method="post">
<select name="employer">
<?php 

for($i = 0; $i < count($employer); $i++)
{
	echo "<option value='".$employer[$i]."'";
	if(!$_POST || $_POST['employer'] == $employer[$i]) { echo "selected='selected'>"; }
	echo $employer[$i]."</option>";
}


?>
</select>
<input type="submit" name="submit" value="submit" />
</form>


When ever I’m submitting the form, it is not displaying the other options in the option menu, only the selected one is shown while others are hidden.

Why this is happening ?

You need to rethink the conditional logic. As it is, if the $_POST array isn’t set (the form hasn’t been submitted) the code is producing this mark-up

<form action="" method="post">
<select name="employer">
<option value='NA'selected='selected'>
NA</option>
<option value='PSU'selected='selected'>
PSU</option>
<option value='Govt.'selected='selected'>
Govt.</option>
<option value='Others'selected='selected'>
Others</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>

I don’t know how browsers work it, but only the last "selected"s value is being assigned to $_POST[‘emloyer’]
Each subsequent one “bumps out” the previous. Hence the blank options.


<?php
$employer = array('NA', 'PSU', 'Govt.', 'Others');
if($_POST)
{
    print_r($_POST);
}

?>
<form action="" method="post">
<select name="employer">
<?php

for($i = 0; $i < count($employer); $i++)
{
    echo "<option value='".$employer[$i]."'";

    if(!$_POST || $_POST['employer'] == $employer[$i]) { echo "selected='selected'"; }

    echo ">".$employer[$i]."</option>";
}

?>

</select>

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

</form>

hehe~~,it’s error in the if and echo “>”.in words if you explain not complent the <option> will miss close label “>”.so the close label “>” should echo out of if!


<?php
if('POST' === $_SERVER['REQUEST_METHOD']){
    echo '<pre>', print_r($_POST, true), '</pre>';
}

$employers = array(
    'NA',
    'PSU',
    'Govt.',
    'Others'
);
?>

<form action="" method="post">
    <select name="employer">
        <?php
        foreach($employers as $index => $employer){
            printf(
                '<option value="&#37;d" %s>
                    %s
                </option>',
                $index,
                (isset($_POST['employer']) && $index == $_POST['employer']) ? 'selected="selected"' : null,
                $employer
            );
        }
        ?>
    </select>
    <input type="submit" name="submit" value="submit" />
</form>