Ana Ban Ana Ban - 1 year ago 105
PHP Question

How to get a subset of $_POST array with keys starting with a prefix

Let's say my

variable looks like:


[user_ID] => 65
[action] => editpost
[originalaction] => editpost
[post_author] => 154
[empl_bd_dd] => 6
[empl_bd_mm] => 5
[empl_bd_yy] => 1987
[empl_gen] => 1
[empl_height] => 155
[empl_weight] => 61
[empl_arra] => 2
[save] => Update
[post_it] => 2
[empl_pay] => J77
[empl_cust] => Married
[empl_lang] => Array
[0] => EN
[1] => FR
[empl_rent] => 1
[name] => Jimmy Nathan
[empl_text] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sed interdum leo. Sed et elit quam, tempor placerat neque. Nullam sapien odio, egestas iaculis dictum ut, congue ullamcorper tellus.
[empl_sk_0] => 6
[empl_sk_1] => 7
[empl_sk_2] => 5


As you can see I prefixed all my form variables with
. Short of having to specify all of them one by one, how do I get all my form variables from
into an array in the least-cost hopefully elegant way? Is there a PHP array function or a combination of them that I can use for this?

Like in
where you can select all elements with a class that starts with
, is there a way I can do this with the array keys in PHP, e.g.

$empl_post = $_POST['empl_*']

EDITED ANSWER - impt correction to @chris 's answer:
has to be the first argument to
, e.g.:

$empl_POST = array_intersect_key($_POST, array_flip(preg_grep('/^empl_/', array_keys($_POST))));

Answer Source
$r = array_intersect_key($_POST, array_flip(preg_grep('/^empl_/', array_keys($_POST))));

they really need to add a PREG_GREP_KEYS flag to preg_grep() so we don't have to do all that mess...

As a function:

function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));