Page 1 of 1

Array Insert Element Before Key

Posted: Fri Jul 21, 2006 9:30 am
by Ollie Saunders
I want to insert an element (with an assoicative key) before another in an array.
Here's how I'm doing it at the moment but is there a better efficent way? At the moment I have to loop through the entire array to find the internal position of a key.

Code: Select all

$letter = array('a' => 10,
                'c' => 8,
                'd' => 7,
                'e' => 6,
                'f' => 5);
print_r($letter);

function insertBefore($beforeKey, $newKey, $newValue)
{
    global $letter;

    // find the position of the key
    $internalPosition = 0;
    $found = false;
    foreach ($letter as $key => $value) {
        if ($key == $beforeKey) {
            $found = true;
            break;
        }
        $internalPosition++;
    }
    if (!$found) {
        throw new Exception('Couldn\'t find');
    }

    // use that position to split array into two halves
    $firstPart = array_slice($letter, 0, $internalPosition);
    $secondPart = array_slice($letter, $internalPosition);

    // reconstruct array
    $letter = $firstPart;
    $letter[$newKey] = $newValue; // new data
    foreach ($secondPart as $key => $value) {
        $letter[$key] = $value;
    }
}

// inserts key 'b' with value of 9 before key 'c'
insertBefore('c', 'b', 9);

print_r($letter);
output:

Code: Select all

Array
(
    [a] => 10
    [c] => 8
    [d] => 7
    [e] => 6
    [f] => 5
)
Array
(
    [a] => 10
    [b] => 9
    [c] => 8
    [d] => 7
    [e] => 6
    [f] => 5
)

Posted: Fri Jul 21, 2006 9:40 am
by feyd
I'd probably use array_keys() and array_values() mixed with array_search() and array_splice() to perform it, then finally array_combine() to bring it all back together.

Posted: Fri Jul 21, 2006 9:45 am
by Ollie Saunders
would that be faster?

Posted: Fri Jul 21, 2006 9:50 am
by feyd
try it, test it, find out. :P

Posted: Fri Jul 21, 2006 9:59 am
by Ollie Saunders
try it, test it, find out. :P
I could. But that would involve Effort.
Effort's on holiday at the moment

=: P