[Solved] PHP Insert value in Array (alphabet key)


Here is addToStack function using array_keys, array_search and array_slice functions:

$arr = array(
    'a' =>  "1",
    'b' =>  "2",
    'c' =>  "3"
);

/**
 * Inserts a new element to stack with offset
 * @param $arr the initial array passed by reference
 * @param $pos string key (position)
 * @param $value inserted value
*/
function addToStack(&$arr, $pos, $value) {
    $keys = array_keys($arr);
    $offset = array_search($pos, $keys);
    $rest = array_slice($arr, $offset);

    $arr[$pos] = $value;
    foreach ($rest as $v) {
        $arr[++$pos] = $v;
    }
}

addToStack($arr, 'b', '4');
print_r($arr);

The output:

Array
(
    [a] => 1
    [b] => 4
    [c] => 2
    [d] => 3
)

0

solved PHP Insert value in Array (alphabet key)