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

时间:2015-02-08 16:14:34

标签: php session

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

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

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

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

为:

返回true
if (isset($_SESSION['variable'])) 

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

2 个答案:

答案 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>';
        }

    }