php - How to check if the given value exists in array

192

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?

422

Answer

Solution:

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

Answer

Solution:

in_array returnstrue if the item is present in the array elsefalse. You can try this -

function productIncart($product_id){
    return in_array($product_id, $_SESSION['cart']);
}
172

Answer

Solution:

try this

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

People are also looking for solutions to the problem: html - Responsinve Form which will initially display data from an PHP variable in a Table

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.