Jump to content

Recommended Posts

Here's another newbie question which I'm confused about. I've used the foreach function to list the contents of the first array. However, on the second array I can't get the same results. I simply get the last result echoed and the other ones are ignored.

 

<?php

$array1 = array("Lisa" => 28,"Jack" => 16,"Ryan" => 35,"Rachel" => 46,"Grace" => 34);

foreach($array1 as $names => $numbers)

echo "Name: $names, Age: $numbers <br />"

?>

<br />

<?php

$beatles = array("Singer 1" => "Paul","Singer 2" => "John","Guitarist" => "George","Drummer" => "Ringo");

foreach($beatles as $roles => $names);

echo "$roles: $names <br />"

?>

 

Can anyone see what I've done wrong here?

Thanks

 

Link to comment
https://forums.phpfreaks.com/topic/191216-inconsistencies-in-foreach-working/
Share on other sites

$names => $numbers

$roles => $names

 

i think you should rename $names in the second one maybe confusing it as $names from the first foreach call

 

or maybe its the ; after foreach($beatles as $roles => $names);

 

or

 

foreach ($beatles as $roles => $names) {

echo '$roles: $names <br />';

}

 

sorry i am very tired but try this.

 


<?php
$array1= array();
$array1 = array("Lisa" => 28,"Jack" => 16,"Ryan" => 35,"Rachel" => 46,"Grace" => 34);
foreach($array1 as $names => $numbers) {
echo "Name: $names, Age: $numbers <br />";
}
?>
<br />
<?php
$beatles = array();
$beatles = array("Singer 1" => "Paul","Singer 2" => "John","Guitarist" => "George","Drummer" => "Ringo");
foreach($beatles as $roles => $names){
echo "$roles: $names <br />";
}
?>

 

also your arrays should be like this

 

$array1 = array();
$array1= array();$array1 = array('Lisa' => '28','Jack' => '16','Ryan' => '35','Rachel' => '46','Grace' => '34');
$beatles = array();
$beatles = array('Singer 1' => 'Paul','Singer 2' => 'John','Guitarist' => 'George','Drummer' => 'Ringo');

Their is nothing wrong with the array or the loop (well kinda)

the problem is you are terminating the loop without doing anything,

So you are doing the loop without any output then displaying the last entry..

 

foreach($beatles as $roles => $names);

should be (Note the semi-colon at the end)

foreach($beatles as $roles => $names)

 

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.