1

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";
        }
    }?>
2
  • 3
    in_array checks values, not keys. Commented May 23, 2017 at 12:59
  • @JonStirling Opps.. then I need to use array_key_exists instead - Thanks Commented May 23, 2017 at 13:08

1 Answer 1

1

Try isset() function.

Example:-

if (isset($_SESSION['data'][$id])) {
  echo "$id in array";
} else {
  echo "$id not in array";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.