简体   繁体   中英

Reset variables inside a 'foreach' loop

As I have really many variables inside my foreach loop, it would be great if I could reset them all at once instead of:

 $variable_one = ''; // Reset to: It is blank for each loop
 $variable_two = '';
 ...
 $variable_hundred = '';

If I were you and had these number of variables which should be set to some value in a loop, I would use an array instead:

$arr = ['first value', 'second value','hundred value'];

Then you can access what you want by index in your loop, so instead of using:

$variable_one

You will use:

$arr[0]

And now you want to reset them all, so you can use array_map() like this:

$arr = array_map(function($val){ return '';}, $arr);

If you have such a high number of variables in your loop, you probably should refactor it to make it simpler. If you are sure that having 100 variables inside a loop is a way to go, you can use the following expression:

$variable_one = $variable_two = $variable_hundred = '';

This will set each variable to '' in one very long line.

Another option is to unset() all these variables in a single function call:

unset($variable_one, $variable_two, $variable_hundred);

But this will not set their value to '' , but unset the variable itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM