Check if key exists in $_SESSION by building index string

Posted by Kim on Stack Overflow See other posts from Stack Overflow or by Kim
Published on 2011-01-08T17:44:38Z Indexed on 2011/01/08 17:54 UTC
Read the original article Hit count: 190

Filed under:
|
|

I need to check if a key exists and return its value if it does.
Key can be an array with subkeys or endkey with a value.

$_SESSION['mainKey']['testkey'] = 'value';
var_dump(doesKeyExist('testkey'));
function doesKeyExist($where) {
  $parts = explode('/',$where);
  $str = '';
  for($i = 0,$len = count($parts);$i<$len;$i++) {
    $str .= '[\''. $parts[$i] .'\']';
  }
  $keycheck = '$_SESSION[\'mainKey\']' . $str;
  if (isset(${$keycheck})) {
    return ${$keycheck};
  }

  // isset($keycheck) = true, as its non-empty. actual content is not checked
  // isset(${$keycheck}) = false, but should be true. ${$var} forces a evaluate content
  // isset($_SESSION['mainKey']['testkey']) = true
}

What am I doing wrong ?
Using PHP 5.3.3.

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays