Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Created June 19, 2013 19:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhrrgn/5817420 to your computer and use it in GitHub Desktop.
Save dhrrgn/5817420 to your computer and use it in GitHub Desktop.
preg_grep_keys() allows you to grep over the keys of an array.
<?php
function preg_grep_keys($pattern, $input) {
return preg_grep($pattern, array_keys($input));
}
@josegonzalez
Copy link

Did this really need a function though?

@dongilbert
Copy link

of course it did

@nateabele
Copy link

This is the best one.

@isarmstrong
Copy link

Better version available in the comments at http://php.net/manual/en/function.preg-grep.php (includes flags, this doesn't support inverse).

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;
}

@warent
Copy link

warent commented Apr 9, 2016

10/10 confirmed best function; using for production scale application

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment