Insyte
Insyte

Reputation: 2236

Function to search associative array keys

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)

Upvotes: 0

Views: 1899

Answers (1)

cmbuckley
cmbuckley

Reputation: 42468

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
}

Upvotes: 1

Related Questions