我知道我可以通过执行以下操作检查会话变量是否存在:
if (isset($_SESSION['variable']))
但是可以通过名称的第一部分检查会话是否存在,例如:
if (isset($_SESSION['var']))
为:
返回trueif (isset($_SESSION['variable']))
或
if (isset($_SESSION['varsomethingelse']))
答案 0 :(得分:2)
<?php
function startsWith($haystack, $needle) {
// search backwards starting from haystack length characters from the end
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
$example = array();
$example['variable'] = 'abc';
$nextToBeSet = 'var';
$is_exist = false;
foreach($example as $k => $v)
{
if(startsWith($k, $nextToBeSet))
{
$is_exist = true;
break;
}
}
if($is_exist)
echo 'exists';
else
echo 'not exists';
的输出:强>
存在
的演示:强>
http://3v4l.org/QBj7A
答案 1 :(得分:1)
您可以直接遍历$ SESSION并在会话密钥中检查是否存在带有strpos的“var”:
$_SESSION = ['variable' => 1, 'variablesomething' => 2, 'variablesomethingelse' => 3,'else' => 3]; // just for testing, you don't need this replace
foreach ($_SESSION as $key => $value) {
if (strpos($key, 'var') > -1)
{
echo 'This key in your Session is set: ' . $key . '<br>';
}
}