- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP: Remove object from array
The unset function can be used to remove array object from a specific index in PHP −
Example
$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') ); var_dump($objectarray); foreach ($objectarray as $key => $object) { if ($key == $index) { unset($objectarray[$index]); } } var_dump($objectarray);
Output
This will produce the following output −
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(5) "n214" } [3]=> array(2) { ["label"]=> string(6) "defabc" ["value"]=> string(5) "03n2" } } 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(5) "03n2" } }
An array with 4 objects is declared and assigned to variable ‘objectarray’. Here, we wish to remove the object from index 2, that is also declared with variable named ‘index’. The foreach loop is used to traverse through the array and when the index value in the traversal matches the index from where the value needs to be removed, the ‘unset’ function is called on that element and the remaining elements are returned as output.
Advertisements