如何使用PHP清除一些php变量(不是所有的php变量)?

时间:2014-10-28 16:42:43

标签: 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' , 'c' , 'd');
   foreach ($ as $key=>$val)
       {
          if (!in_array($key,$dontDelete)) 
             {
               unset($[$key]);
             }
       }
?>

4 个答案:

答案 0 :(得分:2)

$defined_variables = get_defined_vars();
$variables2keep = array("a", "b", "c", "variables2keep");

foreach ($defined_variables as $variable => $value) {
    if (! in_array($variable, $variables2keep)) {
        unset($$variable);
    }
}

Demo

答案 1 :(得分:0)

我认为它不起作用的主要原因是因为你不能以这种方式引用变量名。如果这些名称只是单个关联数组中的索引,那么它可能会起作用。否则,我建议您只列出所有变量,并手动取消设置。

答案 2 :(得分:0)

我知道你已经接受了答案,但它是very risky approach。这是一个不会销毁所有超级全局和其他非预期变量的替代方法。

  • 抓取所有以文件
  • 中的1个字母命名的变量
  • 循环使用
  • 检查他们是否在白名单中
  • 如果不在白名单中,请将其杀死。

$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

答案 3 :(得分:-1)

这是我认为可以满足您需求的唯一方式。在此示例中,$d, $e and $f是将被删除的变量&#34;

$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;

在echo中,您会看到$d, $e and $f将为0.如果这是您想要的话,请切换到null

希望它有所帮助!