Jump to content
Larry Ullman's Book Forums

Couple Of Array Questions, P. 169


Recommended Posts

Thank you for providing a forum like this for followup on your books, Larry. So many people put out a book and then go off world as far as their readers are concerned. Already am looking forward to seeing your advanced books.

 

Have been cruising through the QuickStart Guide and really slowed down at arrays. I've since learned the role of the => (holds) operator, but it was introduced in the book suddenly, with no description, and wasn't listed in the operators table. Had to go online, talk to a friend, and consult other books. But it's good, i know what it is now and how it works.

 

There is a question (i guess confusion) i have from exercise 7.4, multidimensional arrays. In the last 2 lines of code before the close, "<p>$key: $value</p>" produces these two variables on the fly, with no assignment values given. This isn't explained. Are $key and $value preassigned variables that contain all array keys and values?

 

Thanks for any help.

Link to comment
Share on other sites

Hello,

 

You must have taken that line from page 167 rather than 169, and it goes with the previous line:

 

foreach ($books as $key => $value)
{
print "<p>$key: $value</p>\n";
}

 

It means more or less: for each element from the $books array, the key will be represented by the $key variable (you could name it $k or $x if you prefer), and the value will be represented by the $value variable (you could name it $v or $y if you prefer).

 

Since the content of $value is itself an array, this will just print:

PHP VQS: Array

 

PHP 5 Advanced VQP: Array

 

PHP 6 and MySQL 5 VQP: Array

 

If you want to print the content of the $books array and of each of the three arrays it contains (i.e. the title of each book, and below the title of each chapter), use the script on page 169:

 

foreach ($books as $title => $chapters)
{
print "<p>$title";

foreach ($chapters as $number => $chapter)
{
	print "<br />Chapter $number is $chapter";
}
print '</p>';
}

 

You see that here altogether different names are used for the variables. You could write just as well:

 

foreach ($books as $key => $value)
{
print "<p>$key";

foreach ($value as $k => $v)
{
	print "<br />Chapter $k is $v";
}
print '</p>';
}

 

The result would be exactly the same.

 

If you want more examples, have a look at the "foreach" page in the PHP manual:

http://www.php.net/manual/en/control-structures.foreach.php

 

I hope this helps,

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...