PHP | SplObjectStorage key() Function

The SplObjectStorage::key() function is an inbuilt function in PHP which is used to get the index of the currently pointing iterator.

Syntax:

int SplObjectStorage::key()

Parameters: This function does not accept any parameter.



Return Value: This function returns the index at which the iterator currently pointing.

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

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create an empty SplObjectStorage
$str = new SplObjectStorage();
  
$obj = new StdClass;
  
$str->attach($obj, "d1");
  
$str->rewind();
  
// Get current index 
$index  = $str->key();
  
// Print Result
var_dump($index);
?>

chevron_right


Output:

int(0)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create an Empty SplObjectStorage
$str = new SplObjectStorage();
   
$obj1 = new StdClass;
$obj2 = new StdClass;
$obj3 = new StdClass;
$obj4 = new StdClass;
   
$str->attach($obj1, "GeksforGeeks");
$str->attach($obj2, "GFG");
$str->attach($obj3);
$str->attach($obj4, "DSA");
   
$str->rewind();
   
// Iterate and print data on each index
while($str->valid()) {
      
    // Get index 
    $index  = $str->key();
    $object = $str->current(); 
    $data   = $str->getInfo();
   
    var_dump($index, $data);
    $str->next();
}
?>

chevron_right


Output:

int(0)
string(12) "GeksforGeeks"
int(1)
string(3) "GFG"
int(2)
NULL
int(3)
string(3) "DSA"

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.