Log in

View Full Version : Resolved add to existing array



ggalan
05-17-2012, 08:46 PM
i am adding to an existing array and it seems to work like this


$arr[] .= 'a';
$arr[] .= 'b';
$arr[] .= 'c';

but if i wanted it written in 1 line like this, what is the correct way?
this doesnt seem to work


$arr[] .= array('a', 'b', 'c');


re:
array_push seems to work


array_push($arr, 'a', 'b', 'c', 'd');

traq
05-18-2012, 12:54 AM
i am adding to an existing array and it seems to work like this


$arr[] .= 'a';
$arr[] .= 'b';
$arr[] .= 'c';

but if i wanted it written in 1 line like this, what is the correct way?
this doesnt seem to work

First: you shouldn't be using the concatenation assignment ( .= ).
Once that's corrected, both methods will work, but will provide different results:
<?php
$array1[] = 'a';
$array1[] = 'b';
$array1[] = 'c';
var_dump( $array1 );
/* output:
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
BTW, this:
$arr = array();
array_push($arr, 'a','b','c' );
has _exactly_ the same result as the method above (but is less efficient)
*/

$array2[] = array( 'a','b','c' );
var_dump( $array2 );
/* output:
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
*/
I suspect what you want, however, is a simple array construct:
<?php
$array = array( 'a','b','c' );
var_dump( $array );
/* output:
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
*/