Félix Desmeules
Félix Desmeules

Reputation: 49

Checking session array for value (PHP in_array)

My simple shopping cart stores products id's in a session array.

I'm trying to set up an if/else statement to enable/disable my "Add to cart" button based on the product ID being in array or not.

<?php
session_start();

//Show cart array

print_r($_SESSION['cart']);
echo '<br><br>';

//Return "yes" or "no"

$panier = $_SESSION['cart'];
$produit = "5";

if (in_array($produit, $panier)) {
print "yes man!";
} 
else {
print "no man!";
}

?>

I'm making sure 5 is part of the array values by displaying them of this test page, but the second part always returns "no man!"

looks simple enough to me. What am i doing wrong ?

print_r command output is

5,5

no man! 

that is because i've added 2 of the "5" product id to my cart

If I change this line

 print_r($_SESSION['cart']);

for

 print_r($_SESSION);

I get

 Array ( [cart] => 5,3,3,3,3,3,3,3,2 )

 no man!

Upvotes: 1

Views: 2965

Answers (2)

Kevin Kopf
Kevin Kopf

Reputation: 14210

So, according to you, $_SESSION['cart'] = "5,5"; and it means it is a string. So the right code to look up your value is strpos():

$pos = strpos($produit, $_SESSION['cart']);
if($pos !== false) {
    echo "YES";
}
else {
    echo "NO";
}

BUT there's a huge risk to get the wrong answer for this. Imagine, you have two products in your cart - first with id 15 and the other with id 7. You'll be looking for id 5. What would the above code output? It will output "YES".

So, instead of using a string, I suggest you use multidimensional array (if you want to stick with sessions). In this particular case then, the variable $_SESSION["cart"] would be an array and with adding new products it would look like this:

$_SESSION["cart"] = array(); // initial value, don't call it every time or it'll flush your array
$_SESSION["cart"][] = $product_ID;

Or similar to it.

print_r will give you a similarly-looking output:

Array(
    cart => array(
        [0] => 5
        [1] => 17
        [2] => 5
    )
)

Then, in_array should work. But, plan your storing wisely ;)

Upvotes: 3

user3278897
user3278897

Reputation: 1004

As jon asked it is better put always the output of your program But for now I am suspecting your problem is in the in_array check this link A problem about in_array it might help

Upvotes: 0

Related Questions