Re: Array Logic
| From: | David Otton | Date: | Mon, 19 May 2003 18:27:29 +0000 |
| Subject: | Re: Array Logic | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-148192@lists.php.net to get a copy of this message | ||
On Mon, 19 May 2003 09:50:31 -0800, you wrote:
>The question is this, what's the easiest way to add an element to the
>middle of an array with numeric keys and shift all of the other elements
>down one?
I suppose you could do something like this...
$arrA = array("apple", "orange", "banana", "pear",
"peach");
$insertBefore = 3;
$toInsert = "potato";
$arrB = array_merge(array($toInsert), array_slice($arrA, $insertBefore));
$arrC = array_merge(array_slice($arrA, 0, $insertBefore), $arrB);
print_r($arrC);
Which is generalised to inserting n elements, rather than 1.
But it's effectively the same thing with different syntax and much more
memory use. To be honest, I'd bet that your simple loop would be faster. If
I were you I'd wrap your loop up as my_array_insert(), and not worry about
it too much.