0

I'm trying to get the value of a given key if found using the array_key_exists function.

$var = 35;

if(array_key_exists($var, $_SESSION['cart_items']))
{
    //give the value of found key
}
else
{
    $_SESSION['cart_items'][$var] = $anothervar;
}

For now, I only have this:

Array
(
    [35] => 3
    [41] => 6
)

So what I wanted to get is the value 3. Is there a simple way to do this?

wobsoriano
  • 12,348
  • 24
  • 92
  • 162

2 Answers2

1

You can use the variable itself in the array declaration. Just put it between the [] brackets. Such as below. If you echo $the_value after that statement it should be 3.

if(array_key_exists($var, $_SESSION['cart_items'])) {
    $the_value = $_SESSION['cart_items'][$var];
}
else {
    $_SESSION['cart_items'][$var] = $anothervar;
}
Dawson Irvine
  • 322
  • 4
  • 19
1

Don't quite understand, but I assume your $_SESSION['cart_items'] is:

Array
(
    [35] => 3
    [41] => 6
)

Then, to get value 3, all you need is:

$_SESSION['cart_items'][$var]
exiang
  • 559
  • 2
  • 14