1

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;

1 Answer 1

1

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'));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the contribution, but this did not actually work. 1 only want to get the key of the array by the productId. like productId 3 has the key 0, productId 4 has the key 1. When i supply the productId, it should give me only the key associated to that productId.
I understand that but why? What is the end goal to getting the key?
i want to update productQuantity value using the key
I edited, but it would be much easier to use the productId as the key wouldn't it??? Yes, it would.
Yes I caught that. Still, take some seasoned advice as use id as the key.

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.