PHP
How to Prepend an Element to a PHP Array
Learn the easiest way to add a new element to the beginning of a PHP array, shifting existing elements to accommodate the new entry. Ideal for adding headers.
<?php
$fruits = ['banana', 'cherry'];
array_unshift($fruits, 'apple');
print_r($fruits);
// Output:
// Array
// (
// [0] => apple
// [1] => banana
// [2] => cherry
// )
$associative_array = ['b' => 'Banana', 'c' => 'Cherry'];
array_unshift($associative_array, 'Apple');
print_r($associative_array);
// Output (numeric keys are re-indexed, string keys remain):
// Array
// (
// [0] => Apple
// [b] => Banana
// [c] => Cherry
// )
// To prepend multiple elements:
$more_fruits = ['grape', 'kiwi'];
array_unshift($fruits, 'orange', 'pear', ...$more_fruits);
print_r($fruits);
// Output:
// Array
// (
// [0] => orange
// [1] => pear
// [2] => grape
// [3] => kiwi
// [4] => apple
// [5] => banana
// [6] => cherry
// )
?>
How it works: The `array_unshift()` function adds one or more elements to the beginning of an array. All existing elements will be shifted forward, and their numeric keys will be re-indexed starting from 0. String keys, however, remain unchanged. You can pass multiple values as separate arguments or use the spread operator (`...`) with another array to prepend multiple elements efficiently.