problem accessing array element

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mottwsc
Forum Commoner
Posts: 55
Joined: Sun Dec 23, 2007 8:01 pm

problem accessing array element

Post by mottwsc »

I've loaded two rows into an array. I see they are there since I display them. I'm then trying to access 'name' in the first row, but I get an offset error when doing what I do below. Not sure what I need to do to display the first name.

Code: Select all

$name = "Bill";
$zip = "15122";
$contacts[] = array('name' => $name, 'zip' => $zip);
$name = "John";
$zip = "15201";
$contacts[] = array('name' => $name, 'zip' => $zip);

foreach ( $contacts as $contacts )
				{
					echo $contacts['name'].",".$contacts['zip']."<br/>";
				}
echo "looking for Bill:".$contacts[0]['name']."<br/>";
This produces the following output:
Bill,15122
John,15201
Notice: Undefined offset: 0 in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\30_a\game_main_test1.php on line 397 looking for Bill:
mottwsc
Forum Commoner
Posts: 55
Joined: Sun Dec 23, 2007 8:01 pm

RESOLVED

Post by mottwsc »

This was resolved by the following change:

Code: Select all

foreach ( $contacts as $value ) {
	echo $value['name'].",".$value['zip']."<br/>";
}
Post Reply