Flags in PHP Functions
Flags can be used in functions
implicitly using the
return
statement. Let's see
how this is done. Suppose we have
the following function that checks
if all elements of an array are positive
numbers:
<?php
function isPositive($arr) {
$flag = true;
foreach ($arr as $elem) {
if ($elem < 0) {
$flag = false;
}
}
return $flag;
}
?>
Let's rewrite the function code using implicit flags:
<?php
function isPositive($arr) {
foreach ($arr as $elem) {
if ($elem < 0) {
return false;
}
}
return true;
}
?>
How it works: if the required element is found in the array,
we exit the function
(and also the loop) using return
.
But if the required element is not found in the array,
there will be no exit from the function and execution
will reach the return true
command. And
it turns out that the function returns true
as a sign that all elements in the array
are positive.
Create a function that will take an array of numbers as a parameter and check that all elements in this array are even numbers.
Create a function that will take a number as a parameter and check that all digits of this number are odd.
Create a function that will take an array as a parameter and check if there are two identical elements in a row in this array.