This question already has an answer here:
I am trying to overwrite [19] in my array, the first value every time. [19] will not always be the same as it populates off an ID that is passed into the array. I want to replace that first index with a new ID based on certain validation.
I've tried unsetting that value and replacing it but it creates a new entry (shown below).
<pre style='font-size:11px'>
[------- var dumping... -------]
arrcount: 2
Array
(
[19] => Array
(
[quantity] => 1
)
[] => 50
)
</pre>
Rather than have a new entry in the array like [] => 50, I would like to replace [19] with [50] while keeping the quantity value the same. Keeping in mind that these numbers are not static, they are dynamic in the case that it is whatever Id is passed based of outside validation.
</div>
Just assign the value to the new key, and unset the old one.
$arr[$newkey] = $arr[$oldkey];
if (isset($arr[$oldkey])) {
unset($arr[$oldkey]);
}
Welcome to StackOverflow.
array_shift() and then array_unshift will be what you are looking for.
https://www.php.net/manual/en/function.array-unshift.php
If you post a code example we could help more.
Get the first key and the first value.
$first_key = array_key_first($array);
$first_value = $array[$first_key];
/**
* Or for PHP < 7.3
* $first_value = reset($array);
* $first_key = key($array);
*/
Unset the first key and union the remainder with the re-keyed first value.
unset($array[$first_key]);
$array = [50 => $first_value] + $array;
array_shift
won't work for this because it reindexes the array. Keep in mind that if the array happens to have another element with index 50, that element will be removed, since the keys must be unique.