Answers for "filter in php array"

PHP
6

array filter use key

$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
);
Posted by: Guest on November-04-2020
15

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.
 */
Posted by: Guest on February-21-2020
3

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));
?>
Posted by: Guest on November-13-2020
4

php filter array

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

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

$filteredArray = array_filter($numbers, "isPositive");
Posted by: Guest on June-11-2020
-1

array_filter php

$var = [
  'first' => 'one',
  'second' => null,
  'third' => 'three',
];


$filteredArray = array_filter($var);
// output: ['first'=>'one,'third'=>'three']
Posted by: Guest on May-03-2021

Browse Popular Code Answers by Language