0

I am writing a shopping cart session handler class and I find myself repeating this certain chunk of code which searches a multidimensional associative array for a value match.

foreach($_SESSION['cart'] as $k => $v){

    if($v['productID'] == $productID){
        $key = $k;
        $this->found = true;
    }
}

I am repeating this when trying to match different values in the array. Would there be an easy to to create a method whereby I pass the key to search and the value. (Sounds simple now I read that back but for some reason have had no luck)

3
  • instead of hardcoding strings just pass variables for whichever key you're looking for. Commented Jan 14, 2013 at 22:29
  • Literally just findKey($key['SOME_KEY'], $SOME_VALUE) ? No idea why I can't get my head around this simple concept :-S Commented Jan 14, 2013 at 22:31
  • 1
    should be, except instead of 'some_key', do $some_key (I think $, haven't done php in a while, though) so you're using a var instead of the string "some_key" Commented Jan 14, 2013 at 22:32

1 Answer 1

1

Sounds like you want something like this:

function findKey(array $array, $wantedKey, $match) {
    foreach ($array as $key => $value){
        if ($value[$wantedKey] == $match) {
            return $key;
        }
    }
}

Now you can do:

$key = findKey($_SESSION['cart'], 'productID', $productID);

if ($key === null) {
    // no match in the cart
} else {
    // there was a match
}
Sign up to request clarification or add additional context in comments.

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.