Close

April 23, 2018

PHP Add To and Remove Elements From an Array

In this tutorial, I’ll show you eight different ways to add to, remove from and insert elements to/from an array in PHP. PHP array functions used include: array(), array_push(), array_unshift(), array_pop(), array_shift(), array_slice(), count(), array_diff() and array_splice().

Let’s start with our original array:

<?php
// Our original array
$array = array('one', 'two', 'three');

Here’s how you add elements to the end of a PHP array:

<?php
// Add elements to end of array
array_push($array, 'four', 'five');

Here’s how to elements to the beginning of a PHP array:

<?php
// Add elements to beginning of array
array_unshift($array, 'zero');

Here’s how to remove a single element from the end of an array:

<?php
// Remove one element from end of array
array_pop($array);

Here’s how to remove a single element from the beginning of an array:

<?php
// Remove one element from beginning of array
array_shift($array);

Here’s how to GET multiple elements from the end of an array:

<?php
// Get multiple elements from end of array
$lasttwo = array_slice($array, -2);

Here’s how to remove multiple elements from the end of an array and return what’s left:

<?php
// Remove multiple elements from end of array
$length = count($array);
$slice = array_slice($array, 0, $length-2);

Here’s how to remove specific elements (by value) from a PHP array:

<?php
// Remove specific elements from an array
$diff = array_diff($array, array('one', 'four'));

Here’s how to insert an element anywhere into an array:

<?php
// Insert element anywhere in array
array_splice( $array, 2, 0, 'inserted');

If you’d like to learn even more PHP, then consider taking my full PHP course here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.