user1392897
user1392897

Reputation: 851

Looping through $_POST array values with PHP

If I have this $_POST array:

session[1][0]=50&
session[1][1]=60&
session[2][0]=70&
session[3][0]=80

How can I use a for loop to get the value of the session and of the item? I thought this would work but it does not.

foreach ($_POST['session'] as $i => $value) {
    $session = $session[$i];
    $item = $value;

    $query->bindValue(':session', $session, PDO::PARAM_INT);
    $query->bindValue(':item', $value, PDO::PARAM_INT);
    $query->execute();

}

So that the first iteration of the loop would produce $session=1 and $item=50?

Upvotes: 0

Views: 1826

Answers (2)

elfan
elfan

Reputation: 1131

From your code, $_POST['session'][$i] and $value would be the same thing, which contains array(0 => 50, 1 => 60) for the first iteration.

In the first iteration $session is not defined yet, so you cannot access $session[$i].

To get what you want to achieve:

foreach ($_POST['session'] as $i => $value) {
    $session = $i;  //1
    $item = $value[0]; //50, and $value[1] is 60
}

To understand more about what the contents of a variable is, you can print its content using print_r($value) for example, so you will know what its content and structure look like.

UPDATE

To iterate all the values for each session:

foreach ($_POST['session'] as $session => $value) {
    foreach ($value as $item) {
        //do whatever you want here with the $session and $item
        //over all the iterations, here we will have:
        //iteration#1   $session=1, $item=50
        //iteration#2   $session=1, $item=60
        //iteration#3   $session=2, $item=70
        //iteration#4   $session=3, $item=80
    }
}

Upvotes: 1

Indrasis Datta
Indrasis Datta

Reputation: 8618

Assuming you want to print all the values in the variable, you should use nested loop here.

foreach ($_POST['session'] as $i => $value) {  /* Accessing session[1], session[2] ... */
    foreach ($value as $val) {  /* session[1][0], session[1][1] ..... */
        echo $val;
    }
}  

Output:

50&60&70&80

Upvotes: 1

Related Questions