I have an array called 'menu', which when put through print_r, currently outputs:
Array ( [4_00] => Array ( [0] => 1 ), [3_00] => Array ( [0] => 1 ), [7_00] => Array ( [0] => 1 ) )
I want to create an expression that will search this array for any keys beginning with '4_'. I have tried with this:
$matches = preg_grep( '/^4_/', $menu );
But that doesn't seem to work.
Any help?
Much appreciated
I think the function is poorly defined in the manual. The function preg_grep returns an array of the keys where the value of the array matches the regular expression.
You would need a function like this in order for you to work as expected
function preg_grep_keys( $pattern, $input, $flags = 0 ) {
$keys = preg_grep( $pattern, array_keys( $input ), $flags );
$vals = array();
foreach ( $keys as $key ) {
$vals[$key] = $input[$key];
}
return $vals;
}
And if you want to keep things really tight, you could even go like this
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
What is wrong with a good old foreach
loop and a string comparison? It gets the job done.
$results = array();
foreach ($menu as $key => $val) {
if (strncmp($key, '4_', 2) === 0) {
$results[] = array($key, $val);
}
}
print_r($results);