Question about Arrays


I was checking out a tutorial at about arrays. There was this code there and I don’t understand something. Here is the code. It was listed in two chunks, which I have separated by a few spaces:

$books = array(0=>array(‘name’=‘A Book’,‘price’=>9.99),1=>array(‘name’=‘Another Book’,‘price’=>17.99));

<?php echo $books[0]['name']; echo $books[1]['price']; $books[0]['price'] = 12.99; foreach($books as $onebook) { echo $onebook['name'] . " sells for $". $onebook['price'] . "
n"; } ?>


What does the line "foreach($books as $onebook)" do, and why was the variable “$onebook” not declared in the first part of the script?



The best place to start in a case such as this would be the PHP manual entry for foreach(): … oreach.php

It is pretty straightforward once you know what is going on. As its name describes, foreach takes each variable in an array, and assigns them to the second variable (as $secondvar) one at a time, iterating the loop.


Oh I get it! So $books was assigned as $onebook.

thanks. slowly but surely I will get this stuff, I hope!