2

I was wondering if it is possible to create unique variables in a for loop using PHP. I tried the following code but it didn't work:

$level_count = 6

for ($i=1; $i<=$level_count; $i++) {
    $level_ + $i = array();
}

I would like to end up with the variables $level_1, $level_2, $level_3, $level_4, $level_5 and $level_6. How would I achieve this?

2
  • 7
    Arrays have been invented to stop you from doing what you are doing now. Commented Sep 29, 2014 at 20:13
  • Thanks @zerkms I'm pretty new to PHP so I didn't know this approach was frowned upon Commented Sep 29, 2014 at 20:30

3 Answers 3

2
$level_count = 6

for ($i=1; $i<=$level_count; $i++) {
    $l = "level" . $i;
    $$l = array();
}

But Zerkms is right...

$arr = array(array(),array(),array(),array(),array(),array());
Sign up to request clarification or add additional context in comments.

Comments

2

It's much easier if you use arrays for this. Try this one-liner:

$level_count = 6;

$array = array_fill_keys(array_map(function($index) {
                                       return 'level_' . $index;
                                   }, range(1, $level_count)), array());

var_dump($array);

Comments

1

Weird thing (I have no idea why you want to use it), but, just for educational purposes...

$level_count = 6;

for ($i = 1; $i <= $level_count; $i++) {
    $name = 'level_' . $i;
    $$name = array();
}

2 Comments

killed me with 10 seconds :)
@Sebas I spent some time trying to explain why I wrote this code in the first place )))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.