note 102951 deleted from function.array-merge by googleguy

From: Date: Fri, 11 Jan 2013 17:24:51 +0000
Subject: note 102951 deleted from function.array-merge by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192932@lists.php.net to get a copy of this message
Note Submitter: japicoder-NOSPAM at gmail dot com ---- 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: <?php $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: <?php $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' )

« previous php.notes (#192932) next »