We help IT Professionals succeed at work.

PHP: unset all variables beginning with $xyz

hankknight
hankknight asked
on
Can I unset all variables beginning with $xyz without specifying the specific variables?
Comment
Watch Question

No
Web Architect
Commented:
you could... why not...

A way could be loop trough all variables using array of get_defined_vars() and preg_match them and if you find a match do something like this  (untested)


foreach($variables as $val){
    if(preg_match($yourRegularExp, $val)){
       unset(${$val});    
   }
}
ioboxWeb Architect

Commented:
forgot to say, php use a variable inside curly brackets as a variable name.
Great jobox.. I didn't know about that get_defined_vars() function..

Here is a code which does that (no rewards please)
$arr = get_defined_vars();
foreach($arr as $var=>$val)
{
        if(preg_match('/^xyz/',$var))
        {
                unset($var);
        }
}

Open in new window

Sorry.. missed a $
$arr = get_defined_vars();
foreach($arr as $var=>$val)
{
        if(preg_match('/^xyz/',$var))
        {
               unset($$var);
        }
}

Open in new window

A simpler (directly takes the keys of array) and faster (uses strncmp rather than preg_match) version:
<?php
$xyz = 1;
$xyz1 = 2;
$abc = 3;

$arr = array_keys(get_defined_vars());
foreach($arr as $var) if(!strncmp("xyz",$var, 3)) unset($$var);

echo $xyz; // PHP Notice:  Undefined variable: xyz in php.php on line 9
echo $xyz1; // PHP Notice:  Undefined variable: xyz1 in php.php on line 10
echo $abc;
?>

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
You might want to consider a design that used an array or an object instead of a design that relied on the string value of a variable name.  If you grouped the "xyz" variables together as a unit, it would make more sense from a computer-science point of view.  Just a thought, ~Ray

Commented:
Nice one, iobox.