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
PHP: Remove object from array
In PHP, you can remove objects from an array using the unset() function. This function removes an element at a specific index and preserves the remaining array keys.
Using unset() to Remove by Index
The simplest way to remove an object from an array is by specifying its index directly −
<?php
$index = 2;
$objectarray = array(
0 => array('label' => 'abc', 'value' => 'n23'),
1 => array('label' => 'def', 'value' => '2n13'),
2 => array('label' => 'abcdef', 'value' => 'n214'),
3 => array('label' => 'defabc', 'value' => '03n2')
);
echo "Before removal:
";
var_dump($objectarray);
unset($objectarray[$index]);
echo "\nAfter removal:
";
var_dump($objectarray);
?>
Before removal:
array(4) {
[0]=>
array(2) {
["label"]=>
string(3) "abc"
["value"]=>
string(3) "n23"
}
[1]=>
array(2) {
["label"]=>
string(3) "def"
["value"]=>
string(4) "2n13"
}
[2]=>
array(2) {
["label"]=>
string(6) "abcdef"
["value"]=>
string(4) "n214"
}
[3]=>
array(2) {
["label"]=>
string(6) "defabc"
["value"]=>
string(4) "03n2"
}
}
After removal:
array(3) {
[0]=>
array(2) {
["label"]=>
string(3) "abc"
["value"]=>
string(3) "n23"
}
[1]=>
array(2) {
["label"]=>
string(3) "def"
["value"]=>
string(4) "2n13"
}
[3]=>
array(2) {
["label"]=>
string(6) "defabc"
["value"]=>
string(4) "03n2"
}
}
Remove by Condition
You can also remove objects based on specific conditions using a foreach loop −
<?php
$objectarray = array(
0 => array('label' => 'abc', 'value' => 'n23'),
1 => array('label' => 'def', 'value' => '2n13'),
2 => array('label' => 'abcdef', 'value' => 'n214')
);
// Remove object where label is 'def'
foreach ($objectarray as $key => $object) {
if ($object['label'] == 'def') {
unset($objectarray[$key]);
}
}
var_dump($objectarray);
?>
array(2) {
[0]=>
array(2) {
["label"]=>
string(3) "abc"
["value"]=>
string(3) "n23"
}
[2]=>
array(2) {
["label"]=>
string(6) "abcdef"
["value"]=>
string(4) "n214"
}
}
Key Points
When using unset() on array elements:
- Original array keys are preserved (gaps may appear in numeric indices)
- Use
array_values()to reindex the array if needed - Multiple elements can be removed in a single operation
Conclusion
The unset() function is the most efficient way to remove objects from arrays in PHP. Use direct index removal for known positions or combine with loops for conditional removal based on object properties.
Advertisements
