Posts tagged "array"

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";


How to remove elements from an array in PHP

// Create an array
$a = new array("orange", "apple", "pineapple");
 
// Remove the apple from the middle of the array
unset($a[1]);
 
// Create an associative array
$a = new array("dogs" => 4, "cats" => 9, "birds" =>2);
 
// Remove the birds from the array
unset($a['birds']);