how to append an array to another arrays in php -
i have arrays in script
$users = array("a", "b", "c", "d", "e"); $newusers = array("f", "g", "h", "i"); $totalusers = $users + $newusers; by using union operator, tried append $newuser array $users.
and store in $totalusers, after printing $totalusers using print_r($totalusers).
it printed out $users array contents. why ?
i used array_merge($users + $newusers) , printed $users array contents.
finally using 1 of next methods,
method 1:
$totalusers = array_merge(array_values($users), array_values($newusers)); print_r($totalusers); method 2:
array_merge($users, $newusers); print_r($totalusers); i got right output
( [0] => [1] => b [2] => c [3] => d [4] => e [5] => f [6] => g [7] => h [8] => ) what problem, , different between above methods??
the + operator returns right-hand array appended left-hand array; keys exist in both arrays, elements left-hand array used, , matching elements right-hand array ignored.
http://www.php.net//manual/en/language.operators.array.php
in other words, adds elements right hand if keys don't exist in left hand array. explains why nil in case.
array_merge($users + $newusers) this same, array union, , afterwards array_merge on result. nil either.
array_merge($users, $newusers) this want, it's right thing do.
array_merge(array_values($users), array_values($newusers)) this exact same thing well, array_values nil in case.
php
No comments:
Post a Comment