Читать книгу PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO) - Sergey D Skudaev - Страница 13
The foreach loop
ОглавлениеTo use the for loop for an array you have to know how many items the array has. Sometimes, it is more convenient to use the foreach loop. The Foreach loop has the following syntax:
foreach (array_expression as $value)
statement
http://php.net/manual/en/control-structures.foreach.php
If you have an array of names ($names) and you want to greet each person, use the foreach loop to avoid having to know how many names are in the array.
foreach ($names as $aname)
echo “Hello,”. $aname.”! <br>”;
Output:
Hello, John!
Hello, George!
Hello, James!
Hello, Anna!
Hello, Robert!
Hello, John!
Hello, James!
Hello, George!
Hello, Maria!
Hello, Peter!
Hello, James!
In the foreach loop we can read and display not only a value of the array element but its key as well.
foreach (array_expression as $key => $value)
statement
foreach ($names as $key=> $aname)
echo $key.” Hello,”. $aname.”! <br>”;
Output:
0 Hello, John!
1 Hello, George!
2 Hello, James!
3 Hello, Anna!
4 Hello, Robert!
5 Hello, John!
6 Hello, James!
7 Hello, George!
8 Hello, Maria!
9 Hello, Peter!
10 Hello, James!
The number is the array element’s index or key.