Search code examples
phparraysfor-loopunset

php - unset variable from variable array with for loop


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.


Solution

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