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-
?
If you want to access the key of an array in a foreach loop, you use the following syntax: foreach ($array as $key => $value) { ... }
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.
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);
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With