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";
}
}?>
in_arraychecks values, not keys.array_key_existsinstead - Thanks