Array Insert Element Before Key
Posted: Fri Jul 21, 2006 9:30 am
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.
output:
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);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
)