PHP: Remove object from array

PHPServer Side ProgrammingProgramming

The unset function can be used to remove array object from a specific index in PHP −

Example

 Live Demo

$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.

raja
Published on 09-Apr-2020 11:09:04
Advertisements