Skip to content

Instantly share code, notes, and snippets.

@devudit
Created July 9, 2016 01:54
Show Gist options
  • Save devudit/4c9e70bfd4de16c7b410d6d997f0565d to your computer and use it in GitHub Desktop.
Save devudit/4c9e70bfd4de16c7b410d6d997f0565d to your computer and use it in GitHub Desktop.
Get all keys from a array that start with a certain string
<?php
/*
EXAMPLE ARRAY:-
array(
[field_ft_channel_id] => value of field
[field_ft_status] => value of field
[field_ft_author_id] => value of field
[field_id_14] => value of field
[field_id_15] => value of field
[field_id_16] => value of field|value of field
)
Using array_filter_key
*/
$array = array_filter_key($array, function($key) {
return strpos($key, 'field_id_') === 0;
});
/*
Procedural approach:
*/
$only_field_id = array();
foreach ($array as $key => $value) {
if (strpos($key, 'field_id_') === 0) {
$only_field_id[$key] = $value;
}
}
/*
Procedural approach using objects:
*/
$i = new ArrayIterator($array);
$only_field_id = array();
while ($i->valid()) {
if (strpos($key, 'field_id_') === 0) {
$only_field_id[$i->key()] = $i->current();
}
$i->next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment