[SOLVED] How to avoid similar variable repeating with arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

How to avoid similar variable repeating with arrays?

Post 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
User avatar
Wayne
Forum Contributor
Posts: 339
Joined: Wed Jun 05, 2002 10:59 am

Post by Wayne »

I think this is what you are trying to do??

Code: Select all

foreach($array AS $key => $value){
    ${new_value.$key} = $value;
}
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Post by tomfra »

Exactly something like this, thanks :)

I have a lot to learn...

Tomas
Post Reply