Created
July 9, 2016 01:54
-
-
Save devudit/4c9e70bfd4de16c7b410d6d997f0565d to your computer and use it in GitHub Desktop.
Get all keys from a array that start with a certain string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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