ptheofan
ptheofan

Reputation: 2290

PHP SplObjectStorage attach and push to top of the list

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
}

Upvotes: 3

Views: 781

Answers (1)

Baba
Baba

Reputation: 95131

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]

Upvotes: 0

Related Questions