Verifique si la clave existe en $ _SESSION construyendo una cadena de índice

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
}

Usando PHP 5.3.3.

preguntado el 08 de enero de 11 a las 17:01

Not sure what you are doing here. Can you elaborate? Are you checking for values like mainKey/testkey? -

@Pekka: I think doesKeyExist('foo') should look for _SESSION[mainKey][foo] and doesKeyExist('foo/bar') should look for _SESSION[mainKey][foo][bar]. -

What does that mean? ${$var} forces a evaluate content -

@Nabab: It means using the ${$} notation will look for ${$_SESSION['mainKey']['foo']} which is obviously not what OP intended. -

@BoltClock: It actually is what I wanted and I used this method in the past, but I forgot to check if it works on SUPERGLOBALS which it does NOT. Christian Joudrey provided an alternative solution (I was being blinded by my.. arrogance) -

5 Respuestas

Instead of building the string, just check if the key exists within your loop.

Por ejemplo:

function doesKeyExist($where) {
  $parts = explode('/',$where);
  $currentPart = $_SESSION['mainKey'];
  foreach($parts as $part) {
    if (!isset($currentPart[$part])) {
      return false;
    }
    $currentPart = $currentPart[$part];
  }
  return true;
}

Respondido el 08 de enero de 11 a las 20:01

+1 This is much much safer. OP's current code would eventually lead to a use of eval(). - BoltClock ♦

Y si $_SESSION['mainKey'] does not exist? - Gumbo

Just need to add a verification before starting the loop. I took for granted that it does since OP hardcoded in his function. i.e. if (!isset($_SESSION['mainKey'])) return false; - Christian Joudrey

@Christian Joudrey: But he used isset(${$keycheck}) that would check that too if that syntax were possible. - Gumbo

I just tried that out and it doesn't seem to be working. Whether this is a PHP bug or not, I'd rather stick to my solution as it seems cleaner to me. I am copying arrays to memory, but I'm assuming he wouldn't store anything large in the session anyway. - Christian Joudrey

function getByKeys($keys, $array) {
  $value = $array;
  foreach (explode('/', $keys) as $key) {
    if (isset($value[$key])) {
      $value = $value[$key];
    } else {
      return null;
    }
  }
  return $value;
}

Respondido el 08 de enero de 11 a las 20:01

Perhaps I'm misunderstanding the question, but this would appear to be the simplest way of doing it:

function getKey($arr, $key) {
    if (array_key_exists($key, $arr)) {
        return $arr[$key];
    } else {
        return false;
    }
}

$value = getKey($_SESSION['mainKey'], 'testkey');

Respondido el 08 de enero de 11 a las 21:01

He wants something that can search deeper into the array as well. For instance checking if $_SESSION['mainKey']['testkey']['testkey2'] existe. - Christian Joudrey

That's where clarity of the original question is important. - David Powers

You should use $$keycheck, not ${$keycheck}.

The last notation is only if you use the variable inside a string (e.g. "${$keycheck}")

Vea http://php.net/manual/en/language.variables.variable.php for more details about variable variables

Respondido el 08 de enero de 11 a las 20:01

Pero $$keycheck es equivalente a ${$keycheck}, ${$keycheck} is legal syntax outside strings. - BoltClock ♦

Es posible que desee utilizar el eval () php function for this.

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

HTH

Respondido el 08 de enero de 11 a las 21:01

Ew. This is vulnerable in many more ways than I can think of. - BoltClock ♦

I agree, but if he sanitizes the input, I think it's safe. Right? - takinbo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.