检查会话变量是否由其名称的第一部分设置


Check if session variable is set by first part of its name

我知道我可以通过执行以下操作来检查会话变量是否存在:

if (isset($_SESSION['variable']))

但是,是否可以通过会话名称的第一部分来检查会话是否存在,例如:

if (isset($_SESSION['var'])) 

返回true for:

if (isset($_SESSION['variable'])) 

if (isset($_SESSION['varsomethingelse']))
<?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

您可以简单地循环您的$_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>';
        }
    }