0

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.

8
  • 1
    Why should it? $randomnumber is not used anywhere in your for loop code... Commented Jan 8, 2017 at 17:11
  • i want to unset $randomnumber by using for loop. Commented Jan 8, 2017 at 17:13
  • Then just do unset($randomnumber); your array and for loop have nothing to do with your $randomnumber variable Commented Jan 8, 2017 at 17:13
  • on third for loop it should work like "unset($variables[3])" > "unset($randomnumber)" Commented Jan 8, 2017 at 17:14
  • if you have 600 variables to unset, you want to use a for loop :) Commented Jan 8, 2017 at 17:14

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

YOU ARE INCREDIBLE. thank you. i was searching for that for a long time!
count is O(1) like taking a value from a variable, isn't it?
@u_mulder Still you count the array 3 times instead of just once and store the value in an array.
0

simpler and faster solution:

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.