filter array php by value 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");
Example 2: php array filter
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
var_dump(array_filter($arr, function($k) {
return $k == 'b';
}, ARRAY_FILTER_USE_KEY));
var_dump(array_filter($arr, function($v, $k) {
return $k == 'b' || $v == 4;
}, ARRAY_FILTER_USE_BOTH));
?>
Example 3: php filter array
$numbers = [-2, 4, -6, 8, 10];
function isPositive($number)
{
return $number > 0;
}
$filteredArray = array_filter($numbers, "isPositive");
Example 4: 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);