Get an EXACT value in $_POST array

I'm studying php and I'm trying to figure out how to get the string "Juve_Milan" from this var_dump($_POST) :

    array(5) {
    ["Juve_Milan"] => array(2) {
        [0] => string(1)
        "5" [1] => string(1)
        "1"
    }["Inter_Roma"] => array(2) {
        [0] => string(1)
        "4" [1] => string(1)
        "4"
    }["Napoli_Lazio"] => array(2) {
        [0] => string(1)
        "2" [1] => string(1)
        "5"
    }["name"] => string(0)
    "" ["submit"] => string(5)
    "Invia"
}

I could get all of them with:

foreach ($_POST as $param_name => $param_val) {
  echo "<tr><td>".$param_name."</td><td>".$param_val[0]."-".$param_val[1]."</td></tr>";
}

But i want to get them exactly one by one, for example, if i want to get the string "Juve_Milan" or "inter_Roma" how can i do? Without looping, how can i get the string value: "Juve_milan" or "Inter_Roma"? Becouse with the loop i can access them this way : $_POST as $param_name => $param_val But i want to get them without loop, my first attempt was something like $_POST[0][0] but its wrong...

2 answers

  • answered 2019-10-15 15:17 Lukasz Formela

    You could iterate over keys of the main array like this:

    foreach($_POST as $param_name => $param_val) {
        echo "<tr><td>".$param_name."</td></tr>";
    }
    

    This will return each Juve_Milan, Inter_Roma etc. one by one. Although it's part of the code you already have, I believe this will return values you want only.

  • answered 2019-10-15 21:49 gbenga wale

    There are numbers of php array functions you can use. You can use

    array shift

    to remove an element from an array and display it .e.g

    $club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
    $juve = array_shift($club);
    
    echo $juve;// 'juve_millan'
    

    but note that the array is shortened by one element i.e. 'juve_millan' is no more in the array and also note that using

    array_shift

    over larger array is fairly slow

    Array Slice function

    PHP

    array_slice()

    function is used to extract a slice of an array e.g

    $club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
    

    if I want to display

    inter_roma

    or assigned it to a variable, then I can do this

    $roma = array_slice($club, 1, 1);// The first parameter is the array to slice, the second parameter is where to begin(which is one since most programming language array index start from 0 meaning juve_millan is zero, while inter_roma is 1, napoli_lazio is 2) and the length is 1 since i want to return a single element.
    

    I hope you understand