3

I have an array that I want to rename so that the values are stored depending on what number the for loop is on. I tried something like this but its giving me an error.

for ($i =0;$i<4;$i++){

$array.$i = array();

push stuff into array;




}

So at the next iteration the array is called array1, then array2 and so forth. What is the best way to do this.

4
  • To be clear, you're saying that you want to create four different arrays, with names from $array1 to $array4 ? Commented Apr 12, 2012 at 0:03
  • 3
    use a multidimensional array. $array[$i] ... Commented Apr 12, 2012 at 0:04
  • correct. I have different leagues, with different teams. So I want to create an array for each team of each league if that makes any sense. Commented Apr 12, 2012 at 0:05
  • @user541597: it does. So use nested arrays Commented Apr 12, 2012 at 0:07

4 Answers 4

3

To literally answer your question:

$arrayName = 'array' . $i;
$$arrayName = array();
$$arrayName[] = ...

What you really want is a multidimensional array though:

$array[$i] = array();
$array[$i][] = ...;
Sign up to request clarification or add additional context in comments.

Comments

0

You want to use variable variables, in which the double dollar sign indicates that the name of the variable is taken from a variable.

$varname = "array";
for ($i =0;$i<4;$i++){
    $newvarname = $varname . $i
    $$newvarname = new array()
    push stuff into array;
}

I would add that in these cases, a simpler solution is often to use an array in which the desired variable names are indices. So instead of creating $array1, $array2, and so forth, you'd have:

$arrays = array (
    'array1' => array(stuff),
    'array2' => array(stuff),
    'array3' => array(stuff),
    'array4' => array(stuff)
}

At least, I find it easier to keep track of.

Comments

0

You should be able to reference the array using the $$ notation for variable variables (see: http://www.php.net/manual/en/language.variables.variable.php).

So, something like this should work (untested):

for ($i =0;$i<4;$i++){

  $thisArrayName = 'array'.$i;
  $$thisArrayName = array();

  push stuff into array;

}

Comments

0

You need array of array

for ($i =0;$i<4;$i++){

   $array[$i] = array();

    push stuff into 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.