Posts tagged "add element"

Adding an element to the beginning of an array in PHP

// Create an array
$a = new array("apple", "orange");
 
// Prepend an element to the array
array_unshift($a, "raspberry");
 
// Prepend a couple more elements to the array
array_unshift($a, "pineapple", "watermelon");


Adding an element to the end of an array in PHP

There are two ways to add an element to the end of an array.

// Create an array
$a = new array("apple", "orange");
 
// Add an element to the end of the array using the array_push() function
array_push($a, "banana")
 
// Alternative way of adding an element to the end of an array
$a[] = "pineapple";
 
// Adding an element with a key
$a['fruit'] = "watermelon";