Jump to content

Recommended Posts

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.

 

$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:

 

Link to comment
https://forums.phpfreaks.com/topic/219765-problem-accessing-array-element/
Share on other sites

You're reassigning the values to the array within your foreach loop(), so only the last one remains. Making this change fixes it.

 

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.