Home > database >  How to check the session variable contains some specific value
How to check the session variable contains some specific value

Time:06-12

I could retrieve my session variable which represents access locations as follows,

$_SESSION['access']

This session variable contains some strings as follows,

dummy1,dummy2,dummy3,dummy4

As an example $_SESSION['access'] can be dummy1 or dummy1,dummy2 or dummy1,dummy2,dummy3 or dummy2,dummy3,dummy4 likewise. Are there any method to find contains type of function?

Ex:
if($_SESSION['access']`.contains("dummy1")){
//do somthing, 
}

Or do I need to use mysql function to retrieve what I need?

CodePudding user response:

This may be a bit more verbose, but works:

if ( array_key_exists( "access", $_SESSION ) )  {
    $arrVals = explode( ',', $_SESSION["access"]) ;
    $key = "dummy1" ; // doesn't have to be hard-coded here, just for demo
    $b = array_search( $key, $arrVals ) ;
    if ( $b !== false ) {
        /// do your thing
        echo ( "found $key<br/>") ;
        }
    }

CodePudding user response:

Not a method but function - as string is not an object in PHP.

The function is called str_contains.

Use it like this on your example:

if (str_contains($_SESSION['access'], "dummy1")) {
    //do somthing, 
}

The function is part of the language only recently (needs PHP 8).

For older PHP versions strstr was often used for this purpose (it also returns a substring of the original string, but only in case it is contained - which is exactly what we need here).

One would do so like this:

if (strstr($_SESSION['access'], "dummy1")) {
    //do somthing, 
}
  • Related