【发布时间】:2017-10-23 10:42:41
【问题描述】:
试试这个代码:
您使用带有参数 id 的 URL,例如 index.php?id=value
此值将被推入会话中维护的data 数组中。
我希望这个测试总是返回true。但它总是返回false,为什么?
if (in_array($id, $_SESSION['data'])) {
echo "$id in array";
} else {
echo "$id not in array";
}
完整代码:
<?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_array检查值,而不是键。 -
@JonStirling Opps.. 那么我需要改用
array_key_exists- 谢谢
标签: php arrays session boolean