Seperating arrays into variables

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
Jza
Forum Newbie
Posts: 17
Joined: Sat Sep 23, 2006 10:10 am

Seperating arrays into variables

Post by Jza »

Hello,

I have an array that's going to be from 1 to 10, I need to seperate this array into variables. I thought it would be something like this, but it doesn't seem to be working.

Code: Select all

$day = array('1' => '10');

$d1 = $day[1];
$d2 = $day[2];
$d3 = $day[3];
$d4 = $day[4];
$d5 = $day[5];
$d6 = $day[6];
$d7 = $day[7];
$d8 = $day[8];
$d9 = $day[9];
$d10 = $day[10];

echo $d1;
echo ' ';
echo $day[1];
When I 'echo $d1', I want the number 1 to be displayed, but it doesn't work, it display number 10.
Why?

Jeff
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

You're mistaken about the behavioru of the '=>' operator... What you need is here: http://www.php.net/range.

Instead of writing all thos assignements you could do it in a loop, and use variable variables (checkout the section on this subject in the manual too).

Code: Select all

$day = range(1, 10);
for($i = 1; $i < 11; ++$i) {
 ${'d' . $i } = $day[$i];
}
Jza
Forum Newbie
Posts: 17
Joined: Sat Sep 23, 2006 10:10 am

Post by Jza »

ah yes, thank you.

I thought that '=>' would do an array from 1 to 10.
Post Reply