array_filter in php return array? code example

Example 1: php array filter syntax

$numbers = [2, 4, 6, 8, 10];

function MyFunction($number)
{
  return $number > 5;
}

$filteredArray = array_filter($numbers, "MyFunction");

/**
 * `$filteredArray` now contains: `[6, 8, 10]`
 * NB: Use this to remove what you don't want in the array
 * @see `array_map` when you want to alter/change elements
 * in the array.
 */

Example 2: php array_filter

$array = [1, 2, 3, 4, 5];

$filtered = array_filter($array, function($item) {
    return $item != 4; // Return (include) current item if expression is truthy
});

// $filtered = [1, 2, 3, 5]

Tags:

Php Example