Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to delete an array element based on key in PHP?
In PHP, you can delete an array element based on its key using the unset() function. This function removes both the key and its associated value from the array.
Syntax
unset($array_name['key']); unset($array_name[$index]);
Example 1: Deleting from Indexed Array
Here's how to delete an element from a numeric indexed array −
<?php
$fruits = array("Apple", "Banana", "Orange", "Mango");
echo "Original Array:<br>";
print_r($fruits);
// Delete element at index 1 (Banana)
unset($fruits[1]);
echo "\nAfter deleting index 1:<br>";
print_r($fruits);
?>
Original Array:
Array
(
[0] => Apple
[1] => Banana
[2] => Orange
[3] => Mango
)
After deleting index 1:
Array
(
[0] => Apple
[2] => Orange
[3] => Mango
)
Example 2: Deleting from Associative Array
For associative arrays, you can delete elements using their string keys −
<?php
$student_marks = array(
"John" => 85,
"Sarah" => 92,
"Mike" => 78,
"Emma" => 96
);
echo "Original Array:<br>";
print_r($student_marks);
// Delete Mike's record
unset($student_marks["Mike"]);
echo "\nAfter deleting Mike's record:<br>";
print_r($student_marks);
?>
Original Array:
Array
(
[John] => 85
[Sarah] => 92
[Mike] => 78
[Emma] => 96
)
After deleting Mike's record:
Array
(
[John] => 85
[Sarah] => 92
[Emma] => 96
)
Example 3: Deleting from Multidimensional Array
You can also delete entire sub-arrays or specific nested elements −
<?php
$students = array(
"kevin" => array(
"physics" => 95,
"maths" => 90
),
"ryan" => array(
"physics" => 92,
"maths" => 97
)
);
echo "Before deletion:<br>";
echo "Kevin's physics: " . $students['kevin']['physics'] . "<br>";
echo "Ryan's maths: " . $students['ryan']['maths'] . "<br>";
// Delete entire ryan record
unset($students["ryan"]);
echo "\nAfter deleting Ryan's record:<br>";
print_r($students);
?>
Before deletion:
Kevin's physics: 95
Ryan's maths: 97
After deleting Ryan's record:
Array
(
[kevin] => Array
(
[physics] => 95
[maths] => 90
)
)
Key Points
- The
unset()function permanently removes the element from memory - Array indexes are not reordered after deletion in indexed arrays
- Accessing a deleted element will result in an "Undefined index" error
- Use
isset()to check if a key exists before accessing it
Conclusion
The unset() function provides a simple and effective way to delete array elements by key in PHP. Always verify key existence with isset() before accessing deleted elements to avoid runtime errors.
Advertisements
