user1392897 user1392897 - 1 year ago 60
PHP Question

Looping through $_POST array values with PHP

If I have this $_POST array:


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


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

Answer Source

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.


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download