Jump to content

[SOLVED] if statement inside a foreach won't work


DLR

Recommended Posts

Hi all,

 

I suppose the answer is obvoius (to some), but I'mstumped.

 

Everything in the code seems to work well, except the if statement does not change the $c_selected from "" to "selected" for the appropriate value. So I always get the same country displayed, irrespective of the value of $_SESSION['selectcountry'].

 

Any clues?

 

Thanks.

David

 

//set up array to hold country names, same array used for checking input
$country_array = array();
$query = "SELECT country FROM bb_country ORDER BY country ";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$country_array [] = $row['country'];
}

//display select menu using contents of array

echo '<select name="selectcountry" size="1" >';

if(!isset($_SESSION['selectcountry']) OR ($_SESSION['selectcountry'] == "")){
	echo "<option select>Choose country ..</option>";
}

foreach($country_array as $x) {
	if($x == $_SESSION['selectcountry']) {
		$c_selected = "selected";		
	}else {
		$c_selected = "";
	}
	echo "<option value='" . $x  . " " . $c_selected . " '>"  . $x . "</option>";
}
echo "</select>";

Hi Orio,

 

Unfortunately does not change anything. I still get the first name in the list - irrespective of the <option> selected.

 

I have checked the $_SESSION['selectcountry'] variable, it shows the country that has been selected - but I cannot get the "selected " part to work on the drop down list!

Hi,

 

Have implemented changes suggested.

 

1. source code shows <select name="selectcountry" size="1" ><option value= "Botswana" selected = "" >Botswana</option><option value= "Namibia" selected = "selected" >Namibia</option> . . . etc

 

Namibia was the selected country - so this part is working - but not displaying.

 

2. I have changed the "option" code as follows:

echo '<option value= "' . $x . '"' . ' selected = "' . $c_selected . '"' . ' >'  . $x . '</option>';

 

I now get the last name on the list as opposed to the first!

 

Perhaps this is a clue?

 

Thanks

David

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.