Page 1 of 1

array("..."=>"...") doesn't really as

Posted: Sun Apr 27, 2003 6:42 am
by patrikG
I am slightly dumbfounded. The code below assigns various keys and values to the array $countries.
However, when I var_dump the array I only get one value (see Output below).

Anyone got an idea why this is?

Code: Select all

<?php
require_once("class_mysql.inc.php");
$sql=new mod_db;

$countries=array("Middle East"=>"Bahrain", "Middle East"=>"Egypt", "Middle East"=>"Iran", "Middle East"=>"Iraq", "Middle East"=>"Israel", "Middle East"=>"Jordan", "Middle East"=>"Kuwait", "Middle East"=>"Lebanon", "Middle East"=>"Oman", "Middle East"=>"Qatar", "Middle East"=>"Saudia Arabia", "Middle East"=>"Syria", "Middle East"=>"Turkey", "Middle East"=>"United Arab Emirates", "Middle East"=>"Yemen");
var_dump($countries);
foreach($countries as $key=>$value)
	{
	echo "<br><strong>Updating:</strong> $value as $key<br>";
	echo $sql->update("countries","continent='$key'","country='".$value."'");	
	}

$query=$sql->query("SELECT * FROM countries WHERE continent='' ORDER BY country ASC");
while ($country=$sql->arrays("",$query))
	{
	echo """.$country[country]."", ";
	}
?>
Output:

Code: Select all

array(1) &#123; &#1111;"Middle East"]=&gt;  string(5) "Yemen" &#125;
Updating: Yemen as Middle East

Posted: Sun Apr 27, 2003 7:44 am
by pootergeist
because your indices are all named 'middle east' you are effectively overwriting the value of the single key 'middle east' numerous times - you'd need to add another dimension to the array or rename the keys

Code: Select all

$countries=array("Middle East"=>array("Bahrain","Egypt","Iran","Iraq","Israel","Jordan","Kuwait","Lebanon", "Oman","Qatar","Saudia Arabia","Syria","Turkey","United Arab Emirates","Yemen"),"Europe"=>array("United Kingdom","France"));

foreach($countries as $continent=>$country)
	{
	echo '<br />' .$continent. '<br />';
	foreach($country as $indx=>$country_name)
		{
		echo '[' .$indx. '] = ' .$country_name.'<br />';
		}
	}

Posted: Sun Apr 27, 2003 8:33 am
by patrikG
That answer is too simple :P Please find something more complicated (like "PHP 4.1.2 beta is know to have a bug under Apache 3.3 when the keys of your associative array start with 'M'") , so I don't feel REALLY stupid :P

Posted: Sun Apr 27, 2003 10:43 am
by pootergeist
thinking about your script - maybe your best approach would be just to reverse the key=>val pairs - multiple keys can hold the same value - so
"Bahrain"=>"Middle East","Iran"=>"Middle East" would work fine in a foreach loop.

Posted: Sun Apr 27, 2003 10:49 am
by patrikG
Thanks, Pootergeist - you're absolutely right :)