Ollicca Mindstorm
Ollicca Mindstorm

Reputation: 608

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

I know I can check if a session variable exists by doing:

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

But would it be possible to check if the session exists by the first part of its name, so for example:

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

returns true for:

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

or

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

Upvotes: 3

Views: 4104

Answers (2)

Parag Tyagi
Parag Tyagi

Reputation: 8960

<?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';


Output:

exists


Demo:
http://3v4l.org/QBj7A

Upvotes: 2

baao
baao

Reputation: 73221

You can simply loop through your $_SESSION and check for existance of "var" with strpos in your sessions key:

    $_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>';
        }

    }

Upvotes: 1

Related Questions