Summary of “Arrays and loops in PHP: Part 1”

Arrays

An array is a way of storing multiple values in one place. For example:

['ehm', 'cubic', 'tehnodom', 'dg']

The syntax of an array is as follows: the beginning and end of the array are designated by square brackets, and all values, or array elements, are written inside these brackets and separated by commas.

An array can be written to a variable, just like strings and numbers.

$array_name = [element_1, element_2, element_3];

Indexes

All elements in the array have a serial number, i.e., an index. It allows you to access a specific element in the array.

$films = ['Iron Man', 'The Avengers', 'Thor', 'Ant-Man'];
<p><?= $films[0] ?></p>    // Displays the following on the page: "Iron Man"

To access an array element, you must write the array name and the element index in square brackets. The numbering of elements in the array begins with zero.

Writing data to an array by index

Indexes allow you not only to obtain elements, but also to write new data to the array.

Add the following new element to the array $favorite_food:

$favorite_food = ['mashed potatoes', 'meatballs', 'borsch'];
$favorite_food[3] = 'dumplings';
muffin_log ($favorite_food[3]); // Outputs: "dumplings"

Change the value of an element that is already in the array:

$favorite_food = ['mashed potatoes', 'meatballs', 'borsch'];
muffin_log ($favorite_food[1]); // Outputs: "cutlets"
$favorite_food[1] = 'pancakes'  ;
muffin_log ($favorite_food[1]); // Outputs: "pancakes"

The while loop

A loop is a statement that allows you to execute the same code more than once. Loops work great with arrays.

The while loop syntax is similar to the syntax used by conditional statements — it consists of the loop name, loop condition, and loop body. The actions specified in the loop body will be executed repeatedly until the condition becomes false.

while (loop condition) {
  loop body
}
$months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

In order to output all values from this array to the console, use the while loop:

$index = 0;                   // Creates a counter

while ($index < 12) {
  muffin.log($months[$index]);  // Displays the element in the console
  $index = $index + 1;       // Increases the value of the counter
}

Each execution of a block of code in the loop body is called an iteration. The number of iterations must be finite. Otherwise, the loop would run for an infinite number of times, and the page would never finish loading.

To limit the number of iterations, we have created a counter variable: $index. With each iteration, the number in the $index will increase by one. As a result, the elements in the $months array (the numbers 1 to 12) are output sequentially to the console. When the counter value reaches 12, the condition will become false and the loop will stop working.

The while loop in the template

To embed a loop using while in a template, you need to designate the beginning and end of the loop. Then insert the condition, and in the loop body set the element index to increase with each iteration and each time a page markup action is performed.

<?php while (condition): ?>
<li><?= $array[$index] ?></li>
<?php $index = $index + 1 ?>
<?php endwhile;? >

The count command

The count command allows you to calculate the number of elements in the array, which is also known as the array length. To do this, you need to write a set of parentheses after count, and inside the parentheses indicate the name of the array. You can save the obtained value to a variable, which allows you to continue working with it.

$one_to_five = [1, 2, 3, 4, 5];
$number = count($one_to_five);
muffin_log($number); // Outputs: 5

You need to keep in mind that the count command counts the number of elements and not their indexes.

Associative arrays

An array that uses keys instead of indexes is called an associative array. Each key stores a value, and it behaves like a variable. The key name is written in single quotation marks. You need to use the characters => to assign a value to the key.

$spiderman = [
  'name' => 'Peter',    // 'Name' key, value: 'Peter'
  'surname' => 'Parker' // 'Surname' key, value: 'Parker'
];

Both of the array elements from the example refer to Spiderman, so it is convenient not to store them separately as variables, but together in a single array. To get the value from such an array, you need to write the array name and then specify the key in square brackets.

muffin_log($spiderman['name']);    // Outputs: "Peter"
muffin_log($spiderman['surname']); // Outputs: "Parker"

Nested arrays

Arrays may themselves contain other arrays. These arrays are called nested arrays.

$flowers = [
  0 => [
    'name' => 'Chamomile',
    'cost' => 'free'
  ],
  1 => [
    'name' => 'Lily',
    'cost' => 300
  ]
];

The foreach loop

Loop syntax:

foreach ($array as $variable) {
  loop body
}

With each iteration, the next element in the array becomes the value of the variable. Elements are sorted in order from first to last. Therefore, we do not need to use indices. All we need is to reference the variable in the loop body.

The foreach loop in the template

To add this loop to the page markup, we need to write the beginning and end of it, and then we need to insert the page markup actions in the loop body.

$fruits = ['Orange', 'Apple', 'Banana'];

<?php foreach ($fruits as $fruit): ?>
<li><?= $fruit ?></li>
<?php endforeach;? >
// A list of fruits will appear on the page.

Loop conditions

Conditions can be written inside loops. In this case, it is checked whether the condition is true or false at each iteration of the loop. If true, then the actions specified in the condition body will be executed.

$items = ['Table', 'Window', 'Bed'];

<ul class='products-list'>
  <?php foreach($items as $item): ?>
  <?php if ($item === 'Table'): ?>
  // Actions with the page markup
  <?php endif; ?>
  <?php endforeach; ?>
</ul>

For more information on conditions, see the “Conditions” chapter.

“Strict equality” comparison operator

The comparison operator === is frequently used. It is called strict equality, and it checks whether the values to the left and right are equal. If they are equal, then the condition is true.

$item === 'Table'

Continue