1

I am trying to compare the values of 2 arrays with the same key and see if the value of the array with the same key is greater than the other. Here's the arrays:

Array
(
    [3203] => 2
    [7276] => 1
)
Array
(
    [3203] => 1
    [7276] => 1
)

The part of the code that produced the array above:

foreach ($this->request->post['quantity'] as $key => $value)
{           
    $cart_value[$key] = $value;
}

foreach ($this->session->data['cart'] as $id => $val) {

$stock[$id] = $this->cart->availableStock($id);
}

How can I compare the value of each key?

I have this if else statement:

if ($cart_value > $stock) {
  // do something<br>
} elseif ($cart_value = $stock) {
  // do another thing
} else {
  // do this thing
}

Thank you for your help.

1
  • What should happen if one of the values having the same key is bigger than the other? Commented Apr 3, 2015 at 14:42

2 Answers 2

2

Use array_intersect_assoc on the arrays and then use count to see if the result is the same size.

Alternatively, use array_diff_assoc and see if the result is empty.

All depends what you want to do with the result. The first option will return an array containing elements that match, and the second option will return an array containing elements that do not match.

If you want the results to be based on a specific formula (e.g. return only items where the value is greater in the second array), you can use array_uintersect_assoc

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

Comments

0

You can nest foreach loops.

foreach ($array1 as $k1 => $v1) {
    foreach {$array2 as $k2 => $v2) {
        if ($k1 === $k2) {
            switch (true) {

               case ($v1 < $v2):
                   // less than
                   break;
               case ($v1 > $v2):
                   // more than
                   break;
               case ($v1 == $v2):
                   // equal
                   break;
               default:
                   // values cannot be compared
                   break;
            }
        }
    }
}

Comments

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.