Friday, October 10, 2025
HomeLanguagesPHP SplObjectStorage key() Function

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: 

php




<?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);
?>


Output:

int(0)

Program 2: 

php




<?php
  
// Create an Empty SplObjectStorage
$str = new SplObjectStorage();
   
$obj1 = new StdClass;
$obj2 = new StdClass;
$obj3 = new StdClass;
$obj4 = new StdClass;
   
$str->attach($obj1, "neveropen");
$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();
}
?>


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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6718 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS