note 126628 added to function.array-merge
| From: | AndreasHofmann at main dot php dot net | Date: | Sun, 21 Nov 2021 02:59:51 +0000 |
| Subject: | note 126628 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217274@lists.php.net to get a copy of this message | ||
In addition to the text and Julian Egelstaffs comment regarding to keep the keys preserved with the
+ operator:
When they say "input arrays with numeric keys will be renumbered" they MEAN it. If you
think you are smart and put your numbered keys into strings, this won't help. Strings which
contain an integer will also be renumbered! I fell into this trap while merging two arrays with book
ISBNs as keys. So let's have this example:
<?php
$test1['24'] = 'Mary';
$test1['17'] = 'John';
$test2['67'] = 'Phil';
$test2['33'] = 'Brandon';
$result1 = array_merge($test1, $test2);
var_dump($result1);
$result2 = [...$test1, ...$test2]; // mentioned by fsb
var_dump($result2);
?>
You will get both:
array(4) {
[0]=>
string(4) "Mary"
[1]=>
string(4) "John"
[2]=>
string(4) "Phil"
[3]=>
string(7) "Brandon"
}
Use the + operator or array_replace, this will preserve - somewhat - the keys:
<?php
$result1 = array_replace($test1, $test2);
var_dump($result1);
$result2 = $test1 + $test2;
var_dump($result2);
?>
You will get both:
array(4) {
[24]=>
string(4) "Mary"
[17]=>
string(4) "John"
[67]=>
string(4) "Phil"
[33]=>
string(7) "Brandon"
}
The keys will keep the same, the order will keep the same, but with a little caveat: The keys will
be converted to integers.
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 2a01:41e1:2e2c:d200:61d3:59e6:b21b:28b3)
----
Manual Page -- https://php.net/manual/en/function.array-merge.php
Edit -- https://main.php.net/note/edit/126628
Del: integrated -- https://main.php.net/note/delete/126628/integrated
Del: useless -- https://main.php.net/note/delete/126628/useless
Del: bad code -- https://main.php.net/note/delete/126628/bad+code
Del: spam -- https://main.php.net/note/delete/126628/spam
Del: non-english -- https://main.php.net/note/delete/126628/non-english
Del: in docs -- https://main.php.net/note/delete/126628/in+docs
Del: other reasons-- https://main.php.net/note/delete/126628
Reject -- https://main.php.net/note/reject/126628
Search -- https://main.php.net/manage/user-notes.php