One of the many approaches that can be used for this, is to use the function preg_grep
to return items that match a pattern, and to do so, enter the keys of the array with the function array_keys
:
$numeros = array('one' => 1, 'two' => 2, 'three' => 3, 'my_one' => 55, 'my_two' => 33);
$myNumeros = preg_grep('/^my_.*/', array_keys($numeros));
print_r($myNumeros); // [3] => my_one [4] => my_two
See demonstração
Another way to do this is to use the function array_filter
to filter the keys of the array using the function array_keys
, and in the callback, compare the value with strpos
(or stripos
for case-insensitive):
$numeros = array('one' => 1, 'two' => 2, 'three' => 3, 'my_one' => 55, 'my_two' => 33);
$myNumeros = array_filter(array_keys($numeros), function ($chave){
return (strpos($chave, 'my_') !== false);
});
print_r($myNumeros); // [3] => my_one [4] => my_two
See demonstração
I edited the regular expression because the question requires
my_*
, and notmy*
.– Rafael Almeida