如何使用php清除某些php变量(不是所有php变量)?
如何使用php清除某些php变量(不是所有php变量) 我有很多php变量如何使用php清除某些php变量(不是所有php变量)?,php,arrays,Php,Arrays,如何使用php清除某些php变量(不是所有php变量) 我有很多php变量 EG: $a,$b,$c,$d.$e,$f,$g,$h,$i,$j 我想清除所有php变量,但不清除$a、$c、$d 我使用此代码但不工作,我该怎么办 <?PHP $a = "1"; $b = "2"; $c = "3"; $d = "4"; $e = "5"; $f = "6"; $g = "7"; $h = "8"; $i = "9"; $j = "10"; $dontDelete = array('a
EG: $a,$b,$c,$d.$e,$f,$g,$h,$i,$j
我想清除所有php变量,但不清除$a、$c、$d
我使用此代码但不工作,我该怎么办
<?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]);
}
}
?>
我认为它不起作用的主要原因是不能以这种方式引用变量名。如果这些名称只是单个关联数组中的索引,那么它可能会起作用。否则,我建议您只需列出所有变量,并手动取消设置它们。这是我认为唯一适合您需要的方法。在本例中,
$d、$e和$f
是将被“删除”的变量
在echo上,您将看到$d、$e和$f
将为0。如果需要,请切换到null
希望有帮助 我知道你已经接受了答案,但这是一个错误。这里有一个替代方案,它不会破坏所有要删除的超全局变量和其他非预期变量
- 从文件中获取所有以1个字母命名的变量
- 循环通过它们
- 检查他们是否在白名单中
- 如果不在白名单中,杀死他们
您可以使用$arr=get_defined_vars()代码>让我直说吧。。。您想清除不在该数组中的变量,而不是数组本身中的键,对吗?@Ares Draguna,是的,它是正确的。您只想销毁标量,而不是数组或对象,对吗?foreach
行中的$
会给您错误。是的,保存要保留在排除数组中的变量。这是因为您甚至正在清除$variables2keep
。我为您修复了它。请小心使用此解决方案,它将从全局范围中删除所有内容,包括应该保留的a、b和c
变量。不是我认为他想要的。您测试过这段代码吗?正如@riggsfully所说,这是一种非常危险的方法。
$defined_variables = get_defined_vars();
$variables2keep = array("a", "b", "c", "variables2keep");
foreach ($defined_variables as $variable => $value) {
if (! in_array($variable, $variables2keep)) {
unset($$variable);
}
}
$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;
$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