I have array
array (
a => "1",
b => "2",
c => "3"
)
If I Insert "4" at position "b". old value at position b is move to position "c". and old value at position c is move to position "d".
note position "d" is auto create when Insert value. if key in array is a,b,c,d,e,f,g when Insert value in array, It auto create position "h"
So Result is:
array (
a => "1",
b => "4",
c => "2",
d => "3"
)
how do I do? Or have some suggestions
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
)
This trick may help you.
First of all you need to call the function with array
, key
and value
. In function first check for the key is exist or not. if key exist then store the value, now set the value in array with key and value, find the last key using the end
function and then increase the value with one for getting the next character, same if key not exist without storing the value.
$arr = array (
'a' => "1",
'b' => "2",
'c' => "3"
);
function array_push_user($arr, $key, $val){
$store = '';
$bk = '';
if(array_key_exists($key, $arr)){
foreach($arr as $keys => $vals){
if($keys == $key){
$store = $val;
$bk = $vals;
$lst = $keys;
}else{
if($bk != ""){
$store = $bk;
$bk = $vals;
}
else
$store = $vals;
$lst = $keys;
}
$arr[$lst] = $store;
}
$arr[chr(ord($lst)+1)] = $bk;
}else{
end($arr);
$lst = key($arr);
$arr[chr(ord($lst)+1)] = $val;
}
return $arr;
}
$ret_arr = array_push_user($arr, 'b', '4');
echo '<pre>';
print_r($ret_arr);
Result
Array
(
[a] => 1
[b] => 4
[c] => 2
[d] => 3
)