PHP

Using PHP To Delete / Remove Array Keys

When working with arrays in PHP, there may have been a time when you know the exact “key” of the array element that you wish to perform an operation on, such as delete, edit, etc. So do you know how to remove this key from the array so that the associated value is also deleted as well? In this article, I am going to share a very easy way to delete array keys using PHP.

How to use PHP to Remove / Delete Key From Array

In order to remove key from array, let us assume an array of fruits that contains fruit names & they are designated using their keys. Note that removing/deleting a key will also delete/remove the associated value of that key. Let’s look at few examples now.

Example 1: Removing a key from array by using its position

<?php 

//Declare an array
$my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple');

//Print the contents of the array.
echo 'Following are the original array contents:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

//Remove 2nd Key from array i.e. provide a index of 1 as array count starts from 0. The following should delete the mango fruit from the array.
unset($my_fruits_array[1]);

//Print the contents of the array.
echo 'Following are the array contents AFTER removing the key (1) from array using its position:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

?>

Example 2: Removing a key from array using its specified key

<?php

$my_fruits_array = array( 1 => 'apple', 2 => 'mango', 3 => 'grapes', 4 => 'pineapple');

//Print the contents of the array.
echo 'Following are the original array contents:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

//Remove Key from array by using specified key. The following should delete the 3rd key i.e the grapes item will be removed.
unset($my_fruits_array[3]);

//Print the contents of the array. 
echo 'Following are the array contents AFTER removing the key from array, using key name (3):<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

?>

Example 3: Removing a key from array using its name in the array

<?php

$my_fruits_array = array( 'Fruit 1' => 'apple', 'Fruit 2' => 'mango', 'Fruit 3' => 'grapes', 'Fruit 4' => 'pineapple');

//Print the contents of the array.
echo 'Following are the original array contents:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

//Remove Key from array by using key name. The following should delete the 3rd key i.e the grapes item will be removed.
unset($my_fruits_array['Fruit 4']);

//Print the contents of the array. 
echo 'Following are the array contents AFTER removing the key from array, using key name (Fruit 4):<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

?>
That’s it!

Do you know of any other ways to use PHP to delete / remove keys from array? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*