1

I passed 2 arrays through $_POST and am trying to use the data in a php function. I am able to loop through each of the arrays using a foreach loop.

However, I need to loop through one of these arrays while accessing the other one in tandem (ie, on the first element in array1, I need to access the first element of array2)--so a nested foreach loop obviously doesn't help.

I have found that I cannot access the values by numerical index, however--except the first value of the array.

Any help would be greatly appreciated.

Here is the current snippet:

$count = 1;
    foreach ($quantityArray as $quantity):  
        if($quantity < 1){
        ... 
        $order_to_item_idArray[$count]…..
        }
        if($quantity > 0){
        ...             
        $order_to_item_idArray[$count]…...
        }
        ...
    $count = $count + 1;
endforeach;
1
  • You could use a simple for loop? Commented Nov 4, 2014 at 22:29

1 Answer 1

1

You will want to use something like this to achieve what you want:

$a as $key => $c

Here (as pseudo code):

$a = array('dsa','das','asf');
$b = array('aaa','eee','ggg');

foreach ($a as $key => $c)
{
    echo $c . " - " .$b[$key];
}

For your code, the line would be:

foreach ($quantityArray as $key => $quantity) 
Sign up to request clarification or add additional context in comments.

2 Comments

Great--thanks! Why does this work, but not accessing by index, numerically?
Well, it does work with the index, but in your code you are writing $count = 1, but it should be $count = 0 because arrays start with 0, not 1. And you should use $count++ instead of $count = $count + 1. Though I would consider using the $count way bad practice as the one in my answer is way easier and error proof.

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.