0

I want to declare about 100 arrays, like $game1_array, $game2_array ... $game100_array and use them in a calculation. Can I use some sort of look, going from 1 to 100 and declare these in 4 lines rather than declaring them independently?

I tried the following but it didn't work:

for ($i = 1; $i <= 100; $i++) {
$game.'$i'._array = array();
}

Please point out the error.

2
  • it's ${'game'.$i.'_array'} actually. But - why? Commented Nov 8, 2013 at 10:35
  • 3
    Why don't you use array of arrays instead? $game1_array , $game2_array is a really bad design decision Commented Nov 8, 2013 at 10:37

3 Answers 3

5

What you're trying to accomplish is a poor design decision. It's much better to create an array which holds 100 nested arrays.

It could be done with such code:

$games = array_fill(0, 100, array());

Then you can work with them like:

$games[42][] = 'foo'; // would append a 'foo' item into 43rd array
Sign up to request clarification or add additional context in comments.

2 Comments

If the array is numerically indexed and you know the array size, it's probably a better idea to use splFixedArrays
@onetrickpony: indeed, but probably it would be too much for a total newbie :-)
4
for($i=1;$i<=100;$i++)
{
    ${'game'.$i.'_array'} = array();
}

var_dump( $game2_array );

see http://php.net/manual/en/language.variables.variable.php

2 Comments

Could upvoters comment why do you do that? I agree this answer directly answers the question, but don't you think that the major difference between SO and yahoo answers is that we can think here, and that our mission here is to teach people not just blindly give them examples of crappy code?
see, i think pointing out errors in a taken approach is as much part of "the mission" as showing a potentially better one is ... +1 for your answer though ;)
1
for($i=1;$i<=100;$i++){
 $gameArray[$i] = array();
}

Comments

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.