I know how to insert it to the end by:
$arr[] = $item;
But how to insert it to the beginning?
I know how to insert it to the end by:
$arr[] = $item;
But how to insert it to the beginning?
For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
There are two solutions:
$new = ['RLG' => array(1,2,3)];
$array = ['s' => array(2,3), 'l' => [], 'o' => [], 'e' => []];
$arrayWithNewAddedItem = array_merge($new, $array);
array_unshift(array, value1);
Since PHP7.4 you can use the spread opperator, very similar to JavaScript
$arr = [$item, ...$arr];
https://wiki.php.net/rfc/spread_operator_for_array
A few more examples:
// Add an item before
$arr = [$item, ...$arr];
// Add an item after
$arr = [...$arr, $item];
// Add a few more
$arr = [$item1, $item2, ...$arr, $item3];
// Multiple arrays and and items
$arr = [$item1, ...$arr1, $item2, ...$arr2, $item3];
BREAKING Example:
$car = ['brand' => 'Audi', 'model' => 'A8'];
$engine = ['cylinder' => 6, 'displacement' => '3000cc'];
$merged = [...$car, ...$engine];
var_dump($merged);
Will result in:
[ Error ] Cannot unpack array with string keys