0

I have two arrays:

$arr_order:

   Array
    (
        [0] => Array
            (
                [qty] => 5
                [id] => 2
                [sku] => Model 2
            )

        [1] => Array
            (
                [qty] => 2
                [id] => 3
                [sku] => Model 1
            )
    )

$arr_stock:

Array
(
    [0] => Array
        (
            [id] => 2
            [qty] => 2
        )

    [1] => Array
        (
            [id] => 3
            [qty] => 2
        )

)

How can I compare these two arrays using a foreach loop?

Example: If $arr_order[0][qty] =5 > $arr_stock[0][qty] = 2 ...

returns third array:

$arr_stock_available:

Array
    (
        [0] => Array
            (
                [id] => 2
                [qty] => 2
            )
    )
2
  • Hint: foreach ($arr_order as $i => $val) $arr_stock[$i]['qty'] ... Commented Jun 26, 2013 at 6:13
  • Use array_diff to get the diferences: php.net/manual/en/function.array-diff.php Commented Jun 26, 2013 at 6:44

1 Answer 1

1
$i = 0;
$arr_stock_available = array();
foreach($arr_order as $data){
   if($data['qty'] > $arr_stock[$i]['qty']){
       $arr_stock_available[] = $arr_stock[$i];
    } else {
       $arr_stock_available[] = $data;
    }
    $i++;
}

Use the above code.

Sign up to request clarification or add additional context in comments.

4 Comments

For one, you're never incrementing $i, secondly the OP wanted the difference between the stock values.
@deceze I have modified the code. But not found anywhere that OP want the difference of stock values.
@user889349 if you want only the result as you show the above then remove the else part from my answer.
Thanks! Else condition can be removed.

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.