Ceejay
Ceejay

Reputation: 7267

How to check if the given value exists in array

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?

Upvotes: 0

Views: 113

Answers (3)

Sougata Bose
Sougata Bose

Reputation: 31749

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']);
}

Upvotes: 2

Jonas m
Jonas m

Reputation: 2734

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";
  }

Upvotes: 1

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

try this

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

Upvotes: 0

Related Questions