PHP: how to filter array keys by using array? Filter()?

array_filter() The callback function of passes only the value of the array, not the key.

If I have:

$my_array = array("foo" => 1, "hello" => "world");

$allowed = array("foo", "bar");

What is the best way to delete all keys in $my array that are not in the $allowed array?

Output required:

$my_array = array("foo" => 1);

#1 building

I need to do the same thing, but there is a more complex array filter on the button.

This is the way I use a similar approach.

// Filter out array elements with keys shorter than 4 characters
$a = array(
  0      => "val 0", 
  "one"  => "val one", 
  "two"  => "val two", 
  "three"=> "val three", 
  "four" => "val four", 
  "five" => "val five", 
  "6"    => "val 6"
); 

$f = array_filter(array_keys($a), function ($k){ return strlen($k)>=4; }); 
$b = array_intersect_key($a, array_flip($f));
print_r($b);

Output results:

Array
(
    [three] => val three
    [four] => val four
    [five] => val five
)

#2 building

This is used. unset() Less flexible options:

$array = array(
    1 => 'one',
    2 => 'two',
    3 => 'three'
);
$disallowed = array(1,3);
foreach($disallowed as $key){
    unset($array[$key]);
}

The result of print_r($array) is:

Array
(
    [2] => two
)

This method is not applicable if you want to keep the filtered value for later use, but it is not applicable if you are sure not to use it.

#3 building

This is a more flexible solution for using closures:

$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$result = array_flip(array_filter(array_flip($my_array), function ($key) use ($allowed)
{
    return in_array($key, $allowed);
}));
var_dump($result);

Output:

array(1) {
  'foo' =>
  int(1)
}

Therefore, in the feature, you can perform other specific tests.

#4 building

If you are looking for a way to filter an array through strings that appear in keys, you can use:

$mArray=array('foo'=>'bar','foo2'=>'bar2','fooToo'=>'bar3','baz'=>'nope');
$mSearch='foo';
$allowed=array_filter(
    array_keys($mArray),
    function($key) use ($mSearch){
        return stristr($key,$mSearch);
    });
$mResult=array_intersect_key($mArray,array_flip($allowed));

print_r($mResult) is

Array ( [foo] => bar [foo2] => bar2 [fooToo] => bar3 )

Support the adaptation of this answer to regular expressions

function array_preg_filter_keys($arr, $regexp) {
  $keys = array_keys($arr);
  $match = array_filter($keys, function($k) use($regexp) {
    return preg_match($regexp, $k) === 1;
  });
  return array_intersect_key($arr, array_flip($match));
}

$mArray = array('foo'=>'yes', 'foo2'=>'yes', 'FooToo'=>'yes', 'baz'=>'nope');

print_r(array_preg_filter_keys($mArray, "/^foo/i"));

Output

Array
(
    [foo] => yes
    [foo2] => yes
    [FooToo] => yes
)

#5 building

PHP 5.6 in array_filter() flag A third parameter, which you can set to ARRAY_FILTER_USE_KEY Filter with keys instead of values:

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

Obviously, it's not as good as array_intersect_key($my_array, array_flip($allowed)) Elegant, but it does provide additional flexibility to perform arbitrary tests on keys, such as $allowed that can contain regular expression patterns rather than pure strings.

You can also use the ARRAY_FILTER_USE_BOTH Pass both the value and the key to the filter function. This is an example based on the first example, but note that I don't recommend that you use $allowed to encode filter rules like this:

$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed  = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
    $my_array,
    function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
        return isset($allowed[$key]) && (
            $allowed[$key] === true || $allowed[$key] === $val
        );
    },
    ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']

Tags: less PHP

Posted on Sat, 07 Mar 2020 23:07:43 -0500 by --ss--