Adding elements onto an array

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
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Adding elements onto an array

Post 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
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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
)
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

You can use array_push() to do the same thing. And array_unshift() to put them onto the start of the array.
Post Reply