Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find array elements that have a certain key-name prefix

Tags:

arrays

php

I have an associative array with lots of elements and want to get a list of all elements that have a key name with a certain 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',
);
like image 472
Philipp Avatar asked Oct 18 '25 00:10

Philipp


2 Answers

You could 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)
like image 72
w3spi Avatar answered Oct 20 '25 13:10

w3spi


This should work for you:

Just grab all keys which starts with store: with preg_grep() from your array. And then do a simple array_intersect_key() call to get the intersect 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
)
like image 22
Rizier123 Avatar answered Oct 20 '25 15:10

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!