Dec

16


By using the modulous operator - ampersand (%) and PHP build in array function - array_filter, we can easily filter odd numbers from array, let’s take a look at the complete code first:

function is_odd ($element) {
 return $element % 2;
}
$numbers = array(9, 23, 24, 27);
$odds = array_filter($numbers, 'is_odd');
print_r($odds);

Explaination:
The modulous operator (%) returns the remainder of a division. The remainder of any even integer that is divided by two will always be zero. So if the value of $element is an even number, $element % 2 will be zero. So the equivelence of the following code

return 2% 2;

will be:

return 0;

PHP will conveniently interpret 0 as false and any non-zero as true. So the above line of code will be equivelent to:

return false;

To identify a subset of an array based on its values, use the array_filter( ) function. Each value of array is passed to the function named in callback. The returned array contains only those elements of the original array for which the function returns a true value. So by executing the code $odds = array_filter($numbers, 'is_odd');, we can filter all the odd numbers in the array.



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links