How to filter array by value using array_filter() in PHP

array_filter()
is the function which iterates over every value in array and pass them to the callback function. If callback function returns true, then the current value is returned to the output otherwise not. Array keys are always preserved. You can use this function by two ways:
array_filter ( $array, "callback_function_name" ); function callback_function_name(){ return(condition for value); }
OR
array_filter ( $array, function(){ return(condition for value); } );
Below mentioned example of code will explain you that how we can filter the array with array_filter()
Example: Let us consider that you have an array ($array) in which there are integer values (1, 2, 3, …. 10). Now these is a need to print ODD and EVEN numbers separately. In this situation we will use array_filter()
function of PHP which will help us to do this by using it’s callback function as mentioned below:
<?php function odd($value){ return (($value%2)==1); } function even($value){ return (($value%2)!=1); } $array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); $filterArray_Odd = array_filter($array, "odd"); $filterArray_Even = array_filter($array, "even"); // Output the filtered array of Odd Numbers echo "<h3>Odd Numbers:</h3>"; print_r($filterArray_Odd); // Output the filtered array of Even Numbers echo "<h3>Even Numbers:</h3>"; print_r($filterArray_Even); ?>
Output for the above code will be:
Odd Numbers: Array ( [0] => 1 [2] => 3 [4] => 5 [6] => 7 [8] => 9 ) Even Numbers: Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )