Adding and Removing Array Elements in PHP

Jul 10, 2013, by admin

Sometimes working with arrays, we need to add few extra elements to the array or needs to remove element from array. PHP has some built-in functions that are are designed to attach or detach elements from the beginning or ends of a numerically indexed array.

Adding an Element to an array

To begin with, I’ll explain how to add elements to an array. Actually there are two simple ways to add an element to the end of an array in PHP. The first is to “push” the element onto the array using array_push function. This is especially helpful when you want to add multiple elements to the end of the array at once. You can do that using the array_push function with following code:

  1. $myarray = array(‘spiderman’,‘superman’);
  2. array_push($myarray,‘crocodile’);

Using the code above, we created a new array called $myarray and added one elements to it. We then used the array_push function to add one more new element to the array. The new elements would be added to the end of the array in the same order in which you listed them in the function. Therefore, the order of the elements in the array would now be ‘spiderman’, ‘superman’, ‘crocodile’.

If you are just adding a single new element to an existing array, it’s easier to just use empty brackets. Therefore, instead of using array_push($myarray,’crocodile’) we will use $myarray[] = ‘crocodile’.

 

Removing  an Element from an array

If you just want to get the last element out of an array, you can use array_pop function. Using the array_pop function, you can remove the last element in the array and you can even store that value in its own new variable. For example if you have a file name and you want to find out what the file extension. You can do something like the following.

  1. $filename = ‘stye.css’;
  2. $filename = explode(‘.’,$filename);
  3. $extension = array_pop($filename);

The above example code would convert the string stye.css into an array, splitting it wherever a dot appears in the string. We would then end up with an array that has the elements ‘stye’ and ‘css’ in that order. We then use the array_pop function to remove the ‘css’ from the array and store it as a new variable called $extension.