0

I want to check if the given value is present in array or not. Here i have a function where in i will pass one value as parameter. i have a array $_SESSION['cart'] where i have stored multiple values,while iterating the array i want to check if the product_id is in array

i am calling function while iterating array to check if product_id exists

    <?php
        foreach($_SESSION['cart'] as $item):
        getCartitems($item);
        endforeach;
    ?>   

function

function productIncart($product_id){
        //check if the $_SESSION['cart']; has the given product id
        //if yes 
        //return true
        //else
        //return false
}

how can i do this?

1
  • 1
    How your data is structured in $_SESSION['cart']? Commented Oct 6, 2015 at 7:39

3 Answers 3

2

in_array returns true if the item is present in the array else false. You can try this -

function productIncart($product_id){
    return in_array($product_id, $_SESSION['cart']);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can see if a given key of an array is set using the isset function.

<?php
$array = array( "foo" => "bar" );

if( isset( $array["foo"] ) )
{
echo $array["foo"]; // Outputs bar
}

if( isset( $array["orange"] ) )
{
 echo $array["orange"]; 
} else {
 echo "Oranges does not exist in this array!";
}

To check if a given value is in an array, you may use the in_array function.

 if (in_array($product_id, $_SESSION["cart"]))
  {
    return true;
  }
  else
  {
    return false";
  }

2 Comments

Why not just return in_array($product_id, $_SESSION["cart"])? if(bool) { return true; } else { return false; } is just a long way of writing return bool;.
why even return it? Why not just make a shorthand? Why even check the array, in a prober designed piece of software, you are not in doubt of whats in your arrays. From a learning perspective, this makes alot more sense :) But point taken. Dont be pedagogic on Stackoverflow! :D
0

try this

function productIncart($product_id){
  if (in_array($product_id, $_SESSION['cart']))
  {
    return true;
  }
  else
  {
    return false";
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.