0

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?

2
  • are you using ajax? Commented Nov 14, 2016 at 2:54
  • yes using ajax to reoder list items Commented Nov 14, 2016 at 2:59

2 Answers 2

1

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks that makes sense - but how do I iterate through the $value array within the loop so I can access $value[1] for example, where the number of items is unknown?
1

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

1 Comment

thanks yes I ultimately want to use the values in a query - I have updated the question to show this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.