note 128734 added to function.array-merge

From: Date: Thu, 13 Jul 2023 19:27:10 +0000
Subject: note 128734 added to function.array-merge
Groups: php.notes 
Request: Send a blank email to php-notes+get-220693@lists.php.net to get a copy of this message
If you're trying to merge an array with something that evaluates to NULL, you'll get unpredictable results: <?php $a = ['1', '2', '4']; $b = null; var_dump($a); var_dump($b); $c = array_merge($a, $b); // this won't work echo "The merged array is:"; var_dump($c); ?> Depending on your error setting, you might not even get anything at all. Under PHP 7.4: array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "4" } NULL PHP Warning: array_merge(): Expected parameter 2 to be an array, null given in /home/gwyneth/stupid-test.php on line 8 The merged array is: NULL Under PHP 8.{0,1,2}: array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "4" } NULL PHP Fatal error: Uncaught TypeError: array_merge(): Argument #2 must be of type array, null given in /home/gwyneth/stupid-test.php:8 Stack trace: #0 /home/gwyneth/stupid-test.php(8): array_merge() #1 {main} thrown in /home/gwyneth/stupid-test.php on line 8 Depending on your display/debug settings, you might not even get anything. The solution, of course, is to do a quick & dirty test before passing the 2nd argument: <?php $a = ['1', '2', '4']; $b = null; var_dump($a); var_dump($b); $c = array_merge($a, $b ?? []); echo "The merged array is:"; var_dump($c); ?> Which gives the expected result (PHP 7.4 to PHP 8.2): array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "4" } NULL The merged array is:array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "4" } While it's perfectly legitimate to merge empty arrays, null is *not* an empty array! ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.159.168 (proxied: 2001:8a0:7101:9800:d0fa:dbdc:d4f4:e515) ---- Manual Page -- https://php.net/manual/en/function.array-merge.php Edit -- https://main.php.net/note/edit/128734 Del: integrated -- https://main.php.net/note/delete/128734/integrated Del: useless -- https://main.php.net/note/delete/128734/useless Del: bad code -- https://main.php.net/note/delete/128734/bad+code Del: spam -- https://main.php.net/note/delete/128734/spam Del: non-english -- https://main.php.net/note/delete/128734/non-english Del: in docs -- https://main.php.net/note/delete/128734/in+docs Del: other reasons-- https://main.php.net/note/delete/128734 Reject -- https://main.php.net/note/reject/128734 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220693) next »