Home > Article > Backend Development > How to output even or odd numbers in an array using php
Function introduction:
array_filter()
The function uses a callback function to filter the elements in the array.
This function passes each key value in the input array to the callback function. If the callback function returns true, the current key value in the input array is returned to the result array. Array key names remain unchanged.
Online learning video recommendation: php video tutorial
The code sample is as follows:
function odd($var){ // returns whether the input integer is odd return($var & 1); } function even($var){ // returns whether the input integer is even return(!($var & 1)); } $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5); $array2 = array(6, 7, 8, 9, 10, 11, 12); echo "Odd :\n"; print_r(array_filter($array1, "odd")); echo "Even:\n";print_r(array_filter($array2, "even"));
Related article tutorial recommendation: php tutorial
The above is the detailed content of How to output even or odd numbers in an array using php. For more information, please follow other related articles on the PHP Chinese website!