Tips and Tricks

PHP Delete / Remove From Array Examples

A very important concept in PHP is the arrays. So if you are familiar with it, you may have come across a situation where you wanted to use PHP to remove element from array. So do you know how to delete a specific element from array? If not, this article is for you. In this article, I am going to share with you a very easy way to remove or delete element from array. So read on to find out more.

Use PHP to Remove Element From Array – Examples

Let’s take a look at how to remove element from array by using an easy to follow example. Let’s consider that we have an array of fruits & we have a vegetable ( an array item ) that we would like to delete from the array. We are going to look at two ways to delete the array item. The first way would be to use the index of the array element to remove the array element directly. The second way is to use specified key to remove the array item.

Example 1: Use Index to Remove Array element using PHP

<?php 
$fruits = array('apple', 'mango', 'grapes', 'pineapple', 'potato');

//Using index to remove array element
unset( $fruits[4] );

echo '<pre>Result after Using index to remove array element<br />';
print_r($fruits);
echo '</pre>';

//Output
Array
(
&nbsp; &nbsp; [0] => apple
&nbsp; &nbsp; [1] => mango
&nbsp; &nbsp; [2] => grapes
&nbsp; &nbsp; [3] => pineapple
)
?>

Example 2: Use specified key to delete array element using PHP

<?php
//Using the specified key to delete array element
$fruits = array('fruit1' => 'apple', 'fruit2' => 'mango', 'fruit3' => 'grapes', 'fruit4' => 'pineapple', 'fruit5' => 'potato');

unset( $fruits['fruit5'] );

echo '<pre>Result after Using specified key to delete array element<br />';
print_r($fruits);
echo '</pre>';

//Output
Array
(
    [fruit1] => apple
    [fruit2] => mango
    [fruit3] => grapes
    [fruit4] => pineapple
)
?>

Simple, isn’t it?
Do you know of any other ways to remove element from array using PHP? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*