Getiterator and collectionfirst object

Hello
I’m search for the less-effort way to get the first result from a getCollection or getIterator query, without having to write a for each loop.

Usually I write something like:

$boxes = $xpdo->getIterator('Box',array(
   'width' => 40,
));
foreach ($boxes as $idx => $box) {
    echo "Box #{$idx} has an id of {$box->get('id')} and a width of {$box->get('width')}\n";
}

And

$boxes = $xpdo->getIterator('Box',array(
   'width' => 40,
));
$boxes[0]->get('id');

doesn’t work

Can’t you just use getObject() instead of getIterator() if you only want the first result?


With getIterator() you probably could do something like this (but I don’t think that is preferable).

$boxes = $xpdo->getIterator('Box',array(
   'width' => 40,
));
$boxes->rewind();
$box = $boxes->current();
1 Like

In contrast to getIterator() the method getCollection() does indeed return an array, but the array keys are the ids of the boxes in the array.

With $boxes[0] you are trying to access the box in the array with the id = 0.

So you probably have to use the array functions reset() or current() or maybe $boxes[array_key_first($boxes)].

$boxes = $xpdo->getCollection('Box',array(
   'width' => 40,
));
$box = reset($boxes); //or maybe $box = current($boxes);
1 Like

Thanks, finally I can use getObject with query order to get what I want.