Andrei
0
Q:

php array filter

$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed  = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);
2

<?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));
?>

1
$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.
 */
5
$numbers = [-2, 4, -6, 8, 10];

function isPositive($number)
{
  return $number > 0;
}

$filteredArray = array_filter($numbers, "isPositive");
1
Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 9
    [4] => 10
    [6] => 12
)
1
?php
$data= [
    0 => [1, 'test1'],
    1 => [2, 'test2'],
    2 => [3, 'test3'],
];

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

var_dump($ids);
-1

New to Communities?

Join the community