john godstime
john godstime

Reputation: 27

Return array key via array value in multiple array data

My $_SESSION stores array in the format below. All of productId value are unique. I want to get array key using a productId.

Array
(
[0] => Array
    (
        [productId] => 3
        [productQuantity] => 1
    )

[1] => Array
    (
        [productId] => 4
        [productQuantity] => 1
    )

[2] => Array
    (
        [productId] => 5
        [productQuantity] => 1
    )

)

I have tried array_search but its not working. I actually saw a similar question, but the answer was left untold. This is the code i tried but its not displaying anything:

$key = array_search(3,$_SESSION['cart']);
echo $key;

Upvotes: 1

Views: 22

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Since they are unique just re-index by the productId:

$cart = array_column($_SESSION['cart'], null, 'productId');
echo $cart[3]['productQuantity'];

Or:

echo array_column($_SESSION['cart'], null, 'productId')[3]['productQuantity'];

If you'll only ever have those 2 then it makes sense to extract productQuantity and re-index by productId:

$cart = array_column($_SESSION['cart'], 'productQuantity', 'productId');
echo $cart[3];

The array will look like $cart = [3 => 1, 4 => 1, 5 => 1].

Or:

echo array_column($_SESSION['cart'], 'productQuantity', 'productId')[3];

If you really just want the current key for some reason, extract productId and search that (as long as keys are 0 based and sequential:

$key = array_search(3, array_column($_SESSION['cart'], 'productId'));

Upvotes: 1

Related Questions