Find array elements that have a specific key name prefix

I have an associative array with a lot of elements and you want to get a list of all elements that have a key name with a specific prefix.

Example:

$arr = array(
  'store:key' => 1,
  'user' => 'demo',
  'store:foo' => 'bar',
  'login' => true,
);

// this is where I need help with:
// the function should return only elements with a key that starts with "store:"
$res = list_values_by_key( $arr, 'store:' );

// Desired output:
$res = array(
  'store:key' => 1,
  'store:foo' => 'bar',
);

      

+3


source to share


3 answers


You can simply do:

$arr = array(
  'store:key' => 1,
  'user' => 'demo',
  'store:foo' => 'bar',
  'login' => true,
);

$arr2 = array();
foreach ($arr as $array => $value) {
    if (strpos($array, 'store:') === 0) {
        $arr2[$array] = $value;
    }
}
var_dump($arr2);

      



Returns:

array (size=2)
'store:key' => int 1
'store:foo' => string 'bar' (length=3)

      

+1


source


This should work for you:

Just grab all the keys that start store:

with preg_grep()

from your array. Then make a simple call array_intersect_key()

to get the intersection of both arrays.

<?php

    $arr = array(
      'store:key' => 1,
      'user' => 'demo',
      'store:foo' => 'bar',
      'login' => true,
    );

    $result = array_intersect_key($arr, array_flip(preg_grep("/^store:/", array_keys($arr))));
    print_r($result);

?>

      



output:

Array
(
    [store:key] => 1
    [store:foo] => bar
)

      

+1


source


From php 5.6, you can use array_filter :

$return = array_filter($array, function ($e) {
        return strpos($e, 'store:') === 0;
}, ARRAY_FILTER_USE_KEY);

var_dump($return);

      

for earlier versions you can use

$return = array_intersect_key($array, array_flip(array_filter(array_keys($array), function ($e) {
    return strpos($e, 'store:') === 0;
})));

      

Demo .

0


source







All Articles