add an element to the beginning of an array in php

To add an element to the beginning of an array in PHP, you can use the array_unshift function. It takes the array as its first argument, followed by the element(s) to be added to the beginning of the array.

Here's an example:

main.php
$myArray = array('apple', 'banana', 'cherry');
array_unshift($myArray, 'orange');

print_r($myArray); // Output: Array([0] => orange [1] => apple [2] => banana [3] => cherry)
175 chars
5 lines

In this example, the array_unshift function is used to add the string 'orange' to the beginning of the myArray array.

The print_r function is then used to display the updated array, which should now contain 'orange' as the first element.

gistlibby LogSnag