⊗ppPmLpFI 116 of 447 menu

Conditions in Loops in PHP

Conditions can be used within loops. Let's look at an example. Suppose we have the following array:

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

Let's output all elements of this array to the screen:

<?php foreach ($arr as $elem) { echo $elem; } ?>

Now let's apply a condition and output only the elements that are even numbers:

<?php foreach ($arr as $elem) { if ($elem % 2 == 0) { echo $elem; } } ?>

Given an array:

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

Using a foreach loop and the if operator, output the odd elements of the array to the console.

Given an array:

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

Using a foreach loop and the if operator, output to the console those elements of the array that are greater than 3 but less than 10.

Given an array with numbers. Numbers can be positive and negative. Find the sum of the positive elements of the array.

Given an array:

<?php $arr = [10, 20, 30, 50, 235, 3000]; ?>

Output to the screen only those numbers from the array that start with the digit 1, 2, or 5.

Create an array of days of the week. Using a foreach loop, output all days of the week, and output the weekend days in bold.

Create an array of days of the week. Using a foreach loop, output all days of the week, and output the current day in italics. The number of the current day should be stored in the variable $day.

byenru