Welcome Guest, Not a member yet? Register   Sign In
array_merge() is messing with my array keys.
#1

[eluser]TheFuzzy0ne[/eluser]
Hi everyone. I'm having trouble keeping the keys in the right places in an array of company names. I am sure I am falling victim to my own stupidity, so please forgive me if I am missing something obvious.

I've put it into a controller to hopefully make it easier for anyone to test.

Code:
<?php

class Test extends Controller {

    function __construct()
    {
        parent::Controller();
    }

    function index($params="") {
        $this->load->helper('form');

        /**
         * Let's imagine that this is an array of companies passed back
         * from my model.
         * This is going to be used in a dropdown box, and the ID is
         * used as the value.
         */
        $arr = array(
            '3' => 'a company',
            '5' => 'b company',
            '4' => 'c company',
            '2' => 'd company',
            '1' => 'e company'
        );

        echo 'Here we can see that the array keeps the order specified above.<br />';
        echo '<pre>',print_r($arr),'</pre>';

        echo 'Now I merge this array with another array because I need an "Other" option<br />';
        $arr = array_merge($arr, array('other' => 'Other'));

        echo 'Here\'s the new array:<br />';
        echo '<pre>',print_r($arr),'</pre>';

        echo 'Hmmmm... What\'s happened to my array? The keys have been changed!';
    }
}

For those who are happy to take my word for it, the first print_r($arr) displays:

Code:
Array
(
    [3] => a company
    [5] => b company
    [4] => c company
    [2] => d company
    [1] => e company
)

After the array is merged with this one:

Code:
array('other' => 'Other');

...this is the result of the second print_r($arr):

Code:
Array
(
    [0] => a company
    [1] => b company
    [2] => c company
    [3] => d company
    [4] => e company
    [other] => Other
)

Is this PHP being strange, or is it just me being strange? Can anyone else confirm this? I am running "PHP 5.2.4-2ubuntu5.3 with Suhosin-Patch 0.9.6.2", straight from the Ubuntu repositories.

I do have a workaround, and that is to simply append some text to the beginning of the option values, but then I will have to strip it on the server. It's easily done, but is it really necessary?


Messages In This Thread
array_merge() is messing with my array keys. - by El Forum - 10-02-2008, 06:24 AM
array_merge() is messing with my array keys. - by El Forum - 10-02-2008, 06:38 AM
array_merge() is messing with my array keys. - by El Forum - 10-02-2008, 06:49 AM
array_merge() is messing with my array keys. - by El Forum - 10-02-2008, 07:03 AM
array_merge() is messing with my array keys. - by El Forum - 10-02-2008, 07:08 AM
array_merge() is messing with my array keys. - by El Forum - 10-02-2008, 07:12 AM



Theme © iAndrew 2016 - Forum software by © MyBB