Page 1 of 1

Adding elements onto an array

Posted: Thu Dec 07, 2006 8:19 am
by impulse()
I should know the answer to this question and I feel quite embarrassed about asking. If I have an array and I want to add elements onto the array throughout a piece of code, how is it possible. I have the following code at the moment which doesn't give the expected results~:

Code: Select all

$a = array();

$a .= 30;
$a .= 60;
$a .= 200;

print_r($a); # This echos "Array3060200"
echo "\n";
echo count($a); # This echos "1"
I was expecting
Array
(
[0] => 30
[1] => 60
[2] => 200
)
Regards, Stephen

Posted: Thu Dec 07, 2006 8:25 am
by JayBird

Code: Select all

$a = array();

$a[] = 30;
$a[] = 60;
$a[] = 200;

print_r($a);
output

Code: Select all

Array
(
[0] => 30
[1] => 60
[2] => 200
)

Posted: Thu Dec 07, 2006 8:28 am
by onion2k
You can use array_push() to do the same thing. And array_unshift() to put them onto the start of the array.