Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset all variables in PHP script

Trying to unset automatically all variables in script.

Have tried this way:

  echo '<br /> Variables in Script before unset(): <br />';
  print_r(array_keys(get_defined_vars()));
  echo '<br /><br />';
  var_dump(get_defined_vars());

  // Creates string of comma-separated variables(*) for unset.
  $all_vars = implode(', $', array_keys(get_defined_vars()));

  echo '<br /><br />';
  echo '<br />List Variables in Script: <br />';
  echo $all_vars;
  unset($all_vars);

  echo '<br /><br />';
  echo '<br />Variables in Script after unset(): <br />';
  print_r(array_keys(get_defined_vars()));
  echo '<br />';
  var_dump(get_defined_vars());

Why does it not work?

Is there a better way to do this?

Thanks for helping!

(*) It's seems somewhat that it does not really create the variables, but a string that looks like variables...

like image 459
Ash501 Avatar asked Oct 08 '14 01:10

Ash501


People also ask

How can we unset variables in PHP?

The function unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed.

How do you unset multiple values in PHP?

if you see in php documentation there are not available directly remove multiple keys from php array. But we will create our own php custom function and remove all keys by given array value. In this example i created custom function as array_except().

What is the use of unset () function in PHP?

The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so.

How do you unset an array in PHP?

The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array. After removal the associated key and value does not change. Parameter: This function accepts single parameter variable.


1 Answers

Here ya go ->

$vars = array_keys(get_defined_vars());
for ($i = 0; $i < sizeOf($vars); $i++) {
    unset($$vars[$i]);
}
unset($vars,$i);

And to clarify, implode returns "a string representation of all the array elements in the same order". http://php.net/manual/en/function.implode.php

Unset requires the actual variable as a parameter, not just a string representation. Which is similiar to what get_defined_vars() returns (not the actual variable reference). So the code goes through the array of strings, and returns each as a reference using the extra $ in front - which unset can use.

like image 124
airtech Avatar answered Oct 13 '22 19:10

airtech