Question

I have a little situation, I am using the SplObjectStorage object and at some point I need to attach an item but also push it to the top of the list so when I iterate through the items I will get it as first object.

i.e.

$splObj->attach($something)
$splOBj->attach($something2)
$splObj->attach($this_must_be_first);

// When I iterate
foreach($splOBj as $obj) {
    // I need the FIRST item to be the $this_must_be_first
}
Was it helpful?

Solution

Am not sure if this exist for iterators but this is a simple work around with iterator_to_array and array_reverse

$splObj = new SplObjectStorage();

$last = new stdClass();
$last->element = "Last Element";


$splObj->attach(new stdClass());
$splObj->attach(new stdClass());
$splObj->attach($last);

$splArray = iterator_to_array($splObj);
$splArray = array_reverse($splArray);

foreach ($splArray as $obj)
{
    var_dump($obj);
}

Output

object(stdClass)[2]
  public 'element' => string 'Last Element' (length=12)
object(stdClass)[4]
object(stdClass)[3]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top