简体   繁体   中英

in_array alternative for check in PHP

I am using in_array() for checking if the value of the product_id is in the array, but it seems not to work.

This is how I add new product_id with additional info inside my session variable:

$_SESSION['product_list']['premium'][$product_id] = array(                                                         
    "price" => $price,                                                        
    "name" => $name
);

And this is my code for checking if it's already added in the session or not (to prevent duplicates of the same product)

$array_to_check = $_SESSION['product_list']['premium'];

if ( in_array($product_id, $array_to_check) ) {

    echo json_encode( 'already exists' );

} else {

    echo json_encode( 'successfully added' );

}

But I am getting always 'successfully added', eventhough I try to add the same product over and over again.

What is wrong with this code?

You should use array_key_exists -

array_key_exists($product_id, $array_to_check)

$product_id is the key of that depth. in_array checks values.

You can check it as

if(isset($_SESSION['product_list']['premium'][$product_id]))
 {
 //yes
 }
if(isset($_SESSION['product_list']['premium'][$product_id])) {
    echo json_encode('already exists');
} else {
    echo json_encode('successfully added');
}

unless the $_SESSION['product_list']['premium'][$product_id] is empty or false this will get true

I guess you want to check the key in Assoc Array, for that you should use array_key_exists(), in_array() will check the values not the keys.

Eg:

$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM