Jump to content

Inconsistencies in foreach Working


aquastream

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)

 

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.