Thursday, December 11, 2025
HomeLanguagesPHP SplObjectStorage removeAllExcept() Function

PHP SplObjectStorage removeAllExcept() Function

The SplObjectStorage::removeAllExcept() function is an inbuilt function in PHP which is used to remove all objects from storage except for those contains by another storage.

Syntax:

int SplObjectStorage::removeAllExcept()

Parameters: This function accepts a single parameter $obj which specify object storage to be retain.

Return Value: This function does not return any value.

Below programs illustrate the SplObjectStorage::removeAllExcept() function in PHP:

Program 1:




<?php
  
$obj1 = new StdClass;
$obj2 = new StdClass;
$obj3 = new StdClass;
  
$gfg1 = new SplObjectStorage();
$gfg1[$obj1] = "Geeks";
  
$gfg2 = new SplObjectStorage();
$gfg2[$obj1] = "GFG";
$gfg2[$obj2] = "GeeksClasses";
$gfg2[$obj3] = "SUDO";
  
// Count all existing objects
var_dump(count($gfg2));
  
// Remove all objects of $gfg2 from $gfg2
$gfg2->removeAllExcept($gfg1);
  
// Print result after removeAll
var_dump(count($gfg2));
?>


Output:

int(3)
int(1)

Program 2:




<?php
  
$obj1 = new StdClass;
$obj2 = new StdClass;
  
$gfg1 = new SplObjectStorage();
$gfg1[$obj1] = "Geeks";
  
$gfg2 = new SplObjectStorage();
$gfg2[$obj1] = "GFG";
$gfg2[$obj2] = "GeeksClasses";
  
// Count and print all existing objects
var_dump(count($gfg2));
  
// Remove all objects of $gfg1 from $gfg2
$gfg2->removeAllExcept($gfg1);
  
// Print result  
var_dump(count($gfg2));
  
// Result remains same
$gfg2->removeAllExcept($gfg2);
  
// Print result  
var_dump(count($gfg2));
  
?>


Output:

int(2)
int(1)
int(1)

Reference: https://www.php.net/manual/en/splobjectstorage.removeallexcept.php

RELATED ARTICLES

Most Popular

Dominic
32440 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6811 POSTS0 COMMENTS
Nicole Veronica
11950 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12023 POSTS0 COMMENTS
Shaida Kate Naidoo
6943 POSTS0 COMMENTS
Ted Musemwa
7195 POSTS0 COMMENTS
Thapelo Manthata
6889 POSTS0 COMMENTS
Umr Jansen
6880 POSTS0 COMMENTS