Page 1 of 1

How to avoid similar variable repeating with arrays?

Posted: Thu Jun 24, 2004 9:50 am
by tomfra
Ok, here is the problem:

Let's say there is an array with 5 entries that I can grab by using $array[1] , $array[2], $array[3] and so on.

I assigned variables to these arrays such as:

Code: Select all

$new_value1 = $arrayї1];
$new_value2 = $arrayї2];
$new_value3 = $arrayї3];
$new_value4 = $arrayї4];
$new_value5 = $arrayї5];
(the real thing is more complex than this example so I really do have to use variables for the array values)

From the above example you can see that only the number at the end of the variable and the corresponding array number changes.

I would like to replace the 5 lines of code with just one with the help of "range" function so that the code looks like:

Code: Select all

$range = range(1, 5);
$new_valueXX = $array[XX]; - where XX is replaced by the number from $range, then a new value with number 2 is created and so on until it reaches the end number set in $range.

How can I do this? I am still quite new to arrays but I am learning :)

Thanks!

Tomas

Posted: Thu Jun 24, 2004 10:12 am
by Wayne
I think this is what you are trying to do??

Code: Select all

foreach($array AS $key => $value){
    ${new_value.$key} = $value;
}

Posted: Thu Jun 24, 2004 11:53 am
by tomfra
Exactly something like this, thanks :)

I have a lot to learn...

Tomas