Saleh Rezq
Saleh Rezq

Reputation: 321

Why does in_array() always return false?

Try this code:

You use the URL with the parameter id e.g index.php?id=value This value will be pushed into the data array that is maintained within a session.

I expect this test to always return true. But it always returns false, why?

   if (in_array($id, $_SESSION['data'])) {
        echo "$id in array";
    } else {
        echo "$id not in array";
    }

The full code:

<?php

    session_start();

     //uncomment when need to clear the data array.
    //if (isset($_SESSION['data'])) {
    //    unset($_SESSION['data']);
    //    die;
    //}

    if (!isset($_SESSION['data'])) {
        $_SESSION['data'] = [];
    }
    if (isset($_GET['id'])) {
        $id = strval($_GET['id']);

        if (!in_array($id, $_SESSION['data'])) {
            $_SESSION['data'][$id] = "data_$id";
        }

        echo '<pre>';
        print_r($_SESSION['data']);
        echo '</pre>';

        // Why does this always return false?
        if (in_array($id, $_SESSION['data'])) {
            echo "$id in array";
        } else {
            echo "$id not in array";
        }
    }?>

Upvotes: 1

Views: 269

Answers (1)

shubham715
shubham715

Reputation: 3302

Try isset() function.

Example:-

if (isset($_SESSION['data'][$id])) {
  echo "$id in array";
} else {
  echo "$id not in array";
}

Upvotes: 1

Related Questions