Php function to undo given variables

I am currently using this php function:

function if_exist(&$argument, $default = '') { if (isset ($argument)) { echo $argument; } else { echo $default; } } 

I want this function to disable the $ argument (passed by reference) and $ default variables immediately after repeating their value, how can I do this? Thanks in advance.

+7
source share
4 answers

According to the manual for unset :

If the variable skipped by reference is not set () inside, the function destroys only the local variable. The variable in the calling environment will retain the same value as before unset (). called.

I guess this is the problem you are facing. So my suggestion is to just set $argument to NULL . Which, according to NULL docs , "will delete the variable and disable its value."

For example: $argument = NULL;

+12
source

$default is passed by value, so it cannot be undone (except for the local area).

As you have undoubtedly discovered, unset() simply disables the link to $argument . You can (sort) unset $argument as follows:

 $argument = null; 
+2
source

the only way to do this with a function is to use global variables.

 //To unset() a global variable inside of a function, // then use the $GLOBALS array to do so: <?php function foo() { unset($GLOBALS['bar']); } $bar = "something"; foo(); ?> 
+1
source

If var is not an array and passed by reference, unset actually disables the pointer, so it will not affect the original.

However, if var is an array , you can disable its keys. eg:

 $arr = [ 'a' => 1, 'b' => ['c' => 3], ]; function del($key, &$arr) { $key = explode('.', $key); $end = array_pop($key); foreach ($key as $k) { if (is_array($arr[$k]) { $arr = &$arr[$k]; } else { return; // Error - invalid key -- doing nothing } } unset($arr[$end]); } del('b.c', $arr); // $arr = ['a' => 1, 'b' => []] del('b', $arr); // $arr = ['a' => 1] 
0
source

All Articles