Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say my $_POST variable looks like:

<?php

Array
(
    [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 empl_. Short of having to specify all of them one by one, how do I get all my form variables from $_POST 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 CSS where you can select all elements with a class that starts with empl using [class*="empl_"], 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: $_POST has to be the first argument to array_intersect_key, e.g.:

$empl_POST = array_intersect_key($_POST, array_flip(preg_grep('/^empl_/', array_keys($_POST))));
like image 278
Ana Ban Avatar asked May 14 '12 12:05

Ana Ban


People also ask

How do I find the first key of an array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);

How to use extract function in php?

The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.

How do you find the key of an array element?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

Can an array have keys?

No. Arrays can only have integers and strings as keys.


3 Answers

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

Edit - since php 5.6 array_filter now has some new flags that let you access the array key in the filter callback.

function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_filter($input, function($key) use ($pattern, $flags) {
           return preg_match($pattern, $key, $flags);
    }, ARRAY_FILTER_USE_KEY);
}

use

$filtered = preg_grep_keys('/^empl_/', $_POST);
like image 90
goat Avatar answered Sep 18 '22 10:09

goat


function GetPrefixedItemsFromArray($array, $prefix)
{
    $keys = array_keys($array);
    $result = array();

    foreach ($keys as $key)
    {
        if (strpos($key, $prefix) === 0)
        {
            $result[$key] = $array[$key];
        }
    }

    return $result;
}

Then simply call with $myArray = GetPrefixedItemsFromArray($_POST, "empl_");.

like image 37
CodeCaster Avatar answered Sep 20 '22 10:09

CodeCaster


$empl_post = array();
foreach ($_POST as $k => $v) {
    if (strpos($k, 'empl_') !== 0) continue;
    $empl_post[substr($k, 5)] = $v
}

print_r($empl_post);
like image 37
lorenzo-s Avatar answered Sep 20 '22 10:09

lorenzo-s