How to delete or remove array element in PHP?

By Faruque Ahamed Mollick

We can delete or remove array element from an array easily. Using the unset() PHP function, we can delete or remove one element from an array.

We can delete multiple array elements by using PHP unset() functions multiple times. But if we want to delete multiple array elements using one function then we can use PHP array_diff() or array_diff_key() function.

Delete array element using unset()

Suppose we have an array:



$my_arr = array(2,3,5,7,9);

Now we want to remove the 5 which is in index 2. The unset function can remove or delete array element by its array index. Below is the code to remove 5 from the above array:

unset($my_arr[2]);
print_r($my_arr);

Now we can see the array that is given below:

Array
(
    [0] => 2
    [1] => 3
    [3] => 7
    [4] => 9
)

Below is another example of PHP unset():

We have the array:

$obj_colors_arr = array(
 'pen' => 'blue',
 'bag' => 'red',
 'pant' => 'black',
 'shirt' => 'white'
 );

Now we want to remove the array element with index bag. below is the code to do that:

unset($obj_colors_arr['pant']);

Now if we print the array, we will see the new array that is given below:

Array
(
    [pen] => blue
    [bag] => red
    [shirt] => white
)

Remove multiple array element by using array_diff()

Using array dif, we can remove multiple array items by its value just like below:

<?php
$obj_colors_arr = array(
    'pen' => 'blue',
    'bag' => 'red',
    'pant' => 'black',
    'shirt' => 'white'
  );


$new_obj_colors = array_diff($obj_colors_arr, ["red", "white"]);

print_r($new_obj_colors);
?>

Using array_diff() function, we can delete multiple array elements by taking its value.

Remove multiple array elements using array_diff_key() function

Using array_diff_key() PHP function, we can delete multiple array elements by its index easily. Below is the code:

<?php
$obj_colors_arr = array(
    'pen' => 'blue',
    'bag' => 'red',
    'pant' => 'black',
    'shirt' => 'white'
  );

$new_obj_colors = array_diff_key($obj_colors_arr, array('bag'=>'red', 'shirt'=>'white'));
?>

So here we have seen how to remove or delete one or multiple array elements in PHP.

Remove duplicate values from an array in PHP

How to get the array key for a given value in PHP?

Leave a Reply

Your email address will not be published. Required fields are marked *