Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all keys from a array that start with a certain string?

I have an array that looks like this:

array(   'abc' => 0,   'foo-bcd' => 1,   'foo-def' => 1,   'foo-xyz' => 0,   // ... ) 

How can I retain only the elements that start with foo-?

like image 845
Alex Avatar asked Feb 12 '11 16:02

Alex


People also ask

How do you access array keys?

If you want to access the key of an array in a foreach loop, you use the following syntax: foreach ($array as $key => $value) { ... }

How do you filter an array key?

Filtering a PHP array by keys To use the PHP array_filter() function to filter array elements by key instead of value, you can pass the ARRAY_FILTER_USE_KEY flag as the third argument to the function. This would pass the key as the only argument to the provided callback function.

How do I find the first key of an array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);

How do I get the last key of an array?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.


1 Answers

Functional approach:

$array = array_filter($array, function($key) {     return strpos($key, 'foo-') === 0; }, ARRAY_FILTER_USE_KEY); 

Procedural approach:

$only_foo = array(); foreach ($array as $key => $value) {     if (strpos($key, 'foo-') === 0) {         $only_foo[$key] = $value;     } } 

Procedural approach using objects:

$i = new ArrayIterator($array); $only_foo = array(); while ($i->valid()) {     if (strpos($i->key(), 'foo-') === 0) {         $only_foo[$i->key()] = $i->current();     }     $i->next(); } 
like image 81
erisco Avatar answered Sep 20 '22 07:09

erisco