How to Delete an Array Element based on Key in PHP?
Given an array containing elements. The task is to remove empty elements from the array based on the key in PHP.
Example:
Input: Array
(
[0] => 'G'
[1] => 'E'
[2] => 'E'
[3] => 'K'
[4] => 'S'
)
Key = 2
Output: Array
(
[0] => 'G'
[1] => 'E'
[3] => 'K'
[4] => 'S'
)
Below are the approaches to deletean Array element based on key in PHP:
Table of Content
Using unset() Function
The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array. After removal the associated key and value does not change.
Syntax:
unset($variable)
Parameter: This function accepts single parameter variable. It is required parameter and used to unset the element.
Example: Delete an element from one dimensional array.
<?php
// PHP program to delete an array
// element based on index
// Declare arr variable
// and initialize it
$arr = array('G', 'E', 'E', 'K', 'S');
// Display the array element
print_r($arr);
// Use unset() function delete
// elements
unset($arr[2]);
// Display the array element
print_r($arr);
?>
Output
Array ( [0] => G [1] => E [2] => E [3] => K [4] => S ) Array ( [0] => G [1] => E [3] => K [4] => S )
Using array_diff_key()
This PHP script uses array_diff_key() to create a modified array $result by excluding elements with key ‘b’. The output displays the array without the element ‘b’ => ‘Banana’, demonstrating selective removal based on keys.
Example: This example shows the use of the above-mentioned approach.
<?php
// Sample array
$array = array(
'a' => 'Apple',
'b' => 'Banana',
'c' => 'Cherry',
'd' => 'Date'
);
// Delete element with key 'b'
$result = array_diff_key($array, array('b' => true));
// Output the modified array
print_r($result);
?>
Output
Array ( [a] => Apple => Cherry [d] => Date )
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.