php - unset variable from variable array with for loop

368 views Asked by At

i want to create a for loop in order to unset the spesific variables in an array. i cant find any answer on the internet. here is my code.

$randomnumber=242;
$variables= array('var','var2','randomnumber');
for ($i = 0; $i < count($variables); $i++) {
unset($variables[$i]);
}

echo $randomnumber;

output is:

242

i dont know what am i missing. please help me guys. i want to unset "var1", "var2", and "randomnumber" variables in the array of "variables". output should be "undefined variable : $randomnumber" or smth like that.

2

There are 2 answers

3
u_mulder On BEST ANSWER

Code

unset($variables[$i]);

means

unset value with key $i from array $variables

If you want to unset a variable with name $variables[$i] then you should use variable variable:

$randomnumber=242;
$variables= array('var','var2','randomnumber');
for ($i = 0; $i < count($variables); $i++) {

    // variable variable syntax here
    unset(${$variables[$i]});

}

echo $randomnumber;
0
Chris On

simpler and faster solution:

$randomnumber = 242;
$variables = ['var', 'var2', 'randomnumber'];

foreach ($variables as $variableName) {
    unset($$variableName);
}