Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding keys to superglobals in php

Tags:

php

session

Is there any way by which I can add keys to superglobals in php without defining the corresponding values to those key?

For example:

$_SESSION['key']='set';//key` automatically gets defined.

But I want to do something like this

add_key($_SESSION,'key')//key is added to $_SESSION array.

Is it possible?

like image 304
Gautam Kumar Avatar asked Dec 03 '25 19:12

Gautam Kumar


2 Answers

It's possible, you just have to pass the first argument by reference. I'm not sure why you want it though:

add_key(array &$var, $key) {
    if (!array_key_exists($key, $var))
        $var[$key] = NULL;
}
like image 65
Artefacto Avatar answered Dec 06 '25 09:12

Artefacto


Can't you just set it to an empty string? or empty? or NULL?

What is it you want to happen when you access $_SESSION['key'] after calling add_key($_SESSION, 'key')?

like image 34
Carson Myers Avatar answered Dec 06 '25 09:12

Carson Myers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!