note 102951 modified in function.array-merge by danbrown

From: Date: Wed, 16 Mar 2011 14:28:44 +0000
Subject: note 102951 modified in function.array-merge by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-177932@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: <?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' ) --was-- 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' ) http://php.net/manual/en/function.array-merge.php

« previous php.notes (#177932) next »