Page 1 of 1

Seperating arrays into variables

Posted: Sun Oct 22, 2006 9:18 am
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

Posted: Sun Oct 22, 2006 9:23 am
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];
}

Posted: Sun Oct 22, 2006 9:59 am
by Jza
ah yes, thank you.

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