TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Inconsistencies in foreach Working (http://www.talkphp.com/absolute-beginners/5261-inconsistencies-foreach-working.html)

aquastream 02-07-2010 03:08 AM

Inconsistencies in foreach Working
 
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

delayedinsanity 02-07-2010 04:27 AM

php Code:
foreach($beatles as $roles => $names); // Notice the semi-colon?
echo "$roles: $names <br />" // This isn't inside of a loop

// Try this:
foreach ( $beatles as $roles => $names ) {
    echo "$roles: $names<br />";
}

Even though PHP allows you to omit braces in one line situations, it's good to get into the practice of using them anyways.

aquastream 02-07-2010 05:14 AM

Thanks again delayedinsanity. Again it was something rather simple, but it did the job.


All times are GMT. The time now is 09:15 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0