Changing php variable name for loop

I have an array that I want to rename so that the values ​​are stored depending on which number the for loop is on. I tried something like this, but it gave 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, etc. What is the best way to do this.

+3
source share
4 answers

To literally answer your question:

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

What you really want is a multidimensional array:

$array[$i] = array();
$array[$i][] = ...;
+3
source

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

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

, , . $array1, $array2 .. :

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

, .

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 (unverified):

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

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

  push stuff into array;

}
0
source

You need an array array

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

   $array[$i] = array();

    push stuff into array;
}
0
source

All Articles