php array filter by key 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: how can use filter in php7.2

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 9
    [4] => 10
    [6] => 12
)

Example 3: filter value in array php return single value

?php
$data= [
    0 => [1, 'test1'],
    1 => [2, 'test2'],
    2 => [3, 'test3'],
];

$ids = array_map(function($item) {
    return $item[0];
}, $data);

var_dump($ids);

Tags:

Php Example