Filter Array of Objects by Value: 5 PHP Code Examples in 2023
How to Filter PHP arrays Before we get to the more complicated scenario of filtering arrays of objects by value, let's show how to do a PHP array filter in general. This is pretty simple to do using the array_filter function. You pass in the original array as the first parameter and then a function as the second parameter. The array_filter function uses the passed function on each element in the array to determine whether it should get returned. Anything returned truthy (not null or false) will get pushed into the new filtered array. Check out the example below to quickly filter an array in PHP by value. PHP array_filter Code Example // Let's setup a scenario where we need to filter an array by values with cows. $sampleArray = [0 => "horse", 1 => "cow", 2 => "pig", 3 => "cow"]; $filteredArray = array_filter( $sampleArray, function($val){ return $val ===…