Array Insert Element Before Key

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Array Insert Element Before Key

Post 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
)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

would that be faster?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

try it, test it, find out. :P
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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
Post Reply