note 102951 added to function.array-merge
| From: | japicoder-NOSPAM at gmail dot com | Date: | Wed, 16 Mar 2011 14:20:08 +0000 |
| Subject: | note 102951 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-177931@lists.php.net to get a copy of this message | ||
If you need to add the same array N times (with the same keys, of course) to an existing array,
array_merge() will not work because of the same keys. The plus operator (+) still doesn't
resolve the problem because of the keys.
Example:
$args = array();
for($i=0; $i < 3; $i++) {
$args += array('first', 'second', 'three', 'four');
}
print_r($args);
Will give you:
array(
[0] => 'first'
[1] => 'second'
[2] => 'three'
[3] => 'four'
)
The solution is to play with the first key of the array you are adding:
$args = array();
for($i=0; $i < 3; $i++) {
$args += array(sizeof($args)+1 => 'first', 'second', 'three',
'four');
}
print_r($args);
Now it is added as expected:
array(
[0] => 'first'
[1] => 'second'
[2] => 'three'
[3] => 'four'
[4] => 'first'
[5] => 'second'
[6] => 'three'
[7] => 'four'
[8] => 'first'
[9] => 'second'
[10] => 'three'
[11] => 'four'
)
----
Server IP: 80.64.47.13
Probable Submitter: 85.61.18.87
----
Manual Page -- http://www.php.net/manual/en/function.array-merge.php
Edit -- https://master.php.net/note/edit/102951
Del: integrated -- https://master.php.net/note/delete/102951/integrated
Del: useless -- https://master.php.net/note/delete/102951/useless
Del: bad code -- https://master.php.net/note/delete/102951/bad+code
Del: spam -- https://master.php.net/note/delete/102951/spam
Del: non-english -- https://master.php.net/note/delete/102951/non-english
Del: in docs -- https://master.php.net/note/delete/102951/in+docs
Del: other reasons-- https://master.php.net/note/delete/102951
Reject -- https://master.php.net/note/reject/102951
Search -- https://master.php.net/manage/user-notes.php