How to clear some php variable (not all php variable) using PHP ?
i have many php variable
EG: $a,$b,$c,$d.$e,$f,$g,$h,$i,$j
i want to clear all php variable and not clear $a,$c,$d
i use this code but not work, how can i do ?
<?PHP
$a = "1";
$b = "2";
$c = "3";
$d = "4";
$e = "5";
$f = "6";
$g = "7";
$h = "8";
$i = "9";
$j = "10";
$dontDelete = array('a' , 'c' , 'd');
foreach ($ as $key=>$val)
{
if (!in_array($key,$dontDelete))
{
unset($[$key]);
}
}
?>
$defined_variables = get_defined_vars();
$variables2keep = array("a", "b", "c", "variables2keep");
foreach ($defined_variables as $variable => $value) {
if (! in_array($variable, $variables2keep)) {
unset($$variable);
}
}
I think the main reason it won't work is because you can't reference variable names in that way. If those names were merely indexes in a single associative array, it might work. Otherwise, I suggest you simply list all variables, and manually unset them.
This is the only way I see that could fit your needs. In this example, $d, $e and $f
are the variables that will be "deleted"
$a = "1";
$b = "2";
$c = "3";
$d = "4";
$e = "5";
$f = "6";
$g = "7";
$h = "8";
$i = "9";
$j = "10";
$delete = array('d', 'e', 'f');
foreach($delete as $yes){
switch($yes){
case 'a':
$a = 0;
break;
case 'b':
$b = 0;
break;
case 'c':
$c = 0;
break;
case 'd':
$d = 0;
break;
case 'e':
$e = 0;
break;
case 'f':
$f = 0;
break;
case 'g':
$g = 0;
break;
case 'h':
$h = 0;
break;
case 'i':
$i = 0;
break;
case 'j':
$j = 0;
break;
}
}
echo $d . ' ' . $e . ' ' . $f;
at echo you will see that $d, $e and $f
will be 0. Switch to null
if that is what you want.
Hope it helps!
I know you've accepted an answer, but it's a very risky approach. Here's an alternative that won't destroy all superglobals and other non-intended variables to delete.
$arrWhitelist = array("a", "b", "c");
$file = file_get_contents(__FILE__);
preg_match_all('/\$[A-Za-z_]{1}/', $file, $vars);
foreach($vars[0] as $variables) {
$variables = ltrim($variables, "$");
if(in_array($variables, $arrWhitelist) == FALSE ) {
unset($$variables);
}
}
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$a = "1";
$b = "2";
$c = "3";
$d = "4";
$e = "5";
$f = "6";
$g = "7";
$h = "8";
$i = "9";
$j = "10";
$arrWhitelist = array("a", "b", "c");
$file = file_get_contents(__FILE__);
preg_match_all('/\$[A-Za-z_]{1}/', $file, $vars);
foreach($vars[0] as $variables) {
$variables = ltrim($variables, "$");
if(in_array($variables, $arrWhitelist) == FALSE ) {
unset($$variables);
}
}
echo $a; //Output: 1
echo $g; //Ouput: Notice: Undefined variable: g in C:\xampp\htdocs\test.php on line 29