Search code examples
phparraysfiltering

Remove first element from a $_POST array


I am trying to loop through an array to take certain values and set them equal to a variable.

Here is my var_dump on my $_POST array

array(5) {
    ["voter"]=> string(2) "22"
    [1]=> string(1) "1"
    [2]=> string(1) "2"
    [3]=> string(1) "3"
    ["vote"]=> string(4)
)

I want the keys out of the key => value pair from the 2nd key value pair on out and then set that to a variable. How would I achieve this?

So from [1] -> string(1) "1" on out..Ignore the first pair.


Solution

  • Using the method provided by @Xeon06 will certainly work, but will require the $_POST data to be in the order you provided, and if that order changes, so will the results. This method does not care about the order.

    function ext($array, array $keys, $default = NULL)
    {
        $found = array();
        foreach ($keys as $key)
        {
            $found[$key] = isset($array[$key]) ? $array[$key] : $default;
        }
        return $found;
    }
    
    $keys = array(1, 2, 3, 'vote');
    $my_vars = ext($_POST, $keys);
    

    function ext($array, array $keys, $default = NULL) {
        $found = array();
        foreach ($keys as $key) {
            $found[$key] = isset($array[$key]) ? $array[$key] : $default;
        }
        return $found;
    }
    
    $_POST = array('voter' => 'TEST', 1 => 'ONE', 2 => 'TWO', 3 => 'THREE', 'vote' => 'HAMBURGER'); 
    $keys = array(1, 2, 3, 'vote');
    $my_vars = ext($_POST, $keys);
    print_r($my_vars);
    

    OUTPUT
    Array

    (
        [1] => ONE
        [2] => TWO
        [3] => THREE
        [vote] => HAMBURGER
    )