Читать книгу PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO) - Sergey D Skudaev - Страница 17

List

Оглавление

List is a language construction. It is used to assign a list of variables in one operation.

In the line below, I assign array $names from the array example above to a list of variables.

list ($name1, $name2, $name3, $name4, $name5, $name6) = $names;

print ($name5); will print John because it is the 5th name in the array.

Multidimensional Arrays

An example of a two-dimensional array is plane seats. A plane has rows identified by numbers and a few seats in a row identified by letters A, B, C, D, E, and F.

Let us imagine that we have 7 rows with 6 seats in each of the rows. Define an array of seats in a row as $s. Then in two for loops we can create an array of all seats.


$s=array (“A”, “B”, “C”, “D”, “E”, “F”);


for ($i=0; $i <7; $i++) {


$row = $i+1;


for ($j=0; $j <6; $j++) {

$seats [$i] [$j] =$row.$s [$j];


print ($seats [$i] [$j]);


if (($j % 5 ==0) && ($j> 0))


print (”<br>”);

}

}


In an inner J loop, we assign a seat value to the two-dimensional array.

$row = $i +1 because $i starts with 0 and the row starts with 1.

Then we concatenate a row number with a seat letter in $s array.

We insert a line break <br> after every 6 seats.

For that we check if modulo of 5 equals 0. This occurs when $j=5. Since $j starts with 0 we have 6 seats in a row before we insert a break.

Additionally, we check if $j is greater than 0 because 0 modulo 5 gives 0 and creates an extra break we do not want to have.

Output:

1A1B1C1D1E1F

2A2B2C2D2E2F

3A3B3C3D3E3F

4A4B4C4D4E4F

5A5B5C5D5E5F

6A6B6C6D6E6F

7A7B7C7D7E7F

PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO)

Подняться наверх