Foreach Loop in PHP

The foreach loop is used to iterate through all elements of an array.

The syntax is as follows: the keyword foreach is written, followed by parentheses (). These parentheses specify the variable containing the array to be iterated, then the word as, and after it - the variable into which, on each iteration of the loop, an array element will be placed. Then come the curly braces {}, which will contain the loop body.

So, the syntax of our loop looks like this:

php<?php
  foreach ($arrayName as $elementName) {
    /*
      The code located between the curly
      braces will repeat as many times
      as there are elements in the array.
    */
  }
?>

Let's use the foreach loop to display all elements of the array on the screen:

php<?php
  $arr = [1, 2, 3, 4, 5];
  
  foreach ($arr as $elem) {
    echo $elem;
  }
?>
Задание 1

Given an array with numbers:

php<?php
  $arr = [1, 2, 3, 4, 5];
?>

Iterate through this array using a loop and display the squares of these numbers on the screen.

Задание 2

Given an array with numbers:

php<?php
  $arr = [1, 2, 3, 4, 5];
?>

Using the foreach loop and the br tag, display a column of elements from this array on the screen.

Задание 3

Given an array with numbers:

php<?php
  $arr = [1, 2, 3, 4, 5];
?>

Using the foreach loop and the br tag, display a column of elements from this array on the screen so that each element of the array is within its own b tag.