Home » Php » arrays – "iterate" a single object or the index equivalent of a php object

arrays – "iterate" a single object or the index equivalent of a php object

Posted by: admin July 12, 2020 Leave a comment

Questions:

I can get where I’m going, but I want the prettiest road.

What led me here was researching the best way to run a function that returns a collection of objects like $dom->getElementsByTagName() or $pdo->query('SELECT itcher FROM scratches')and then – knowing that it will only have one result – accessing that result.

I’ve done some research but I’d like to know that I know all that there is to know.

foreach or anything that iterates over multiple things felt silly from an aesthetic point-of-view because I know there’s just one. Casting it to an array feels like a blemish, and I want to get off to my code. The one I like the most so far is $object->{'0'} because it’s as close to $object[0] as I’ve found, but it doesn’t seem to work in every case. Is there something even prettier to look at? For instance, what exactly is foreach($key as $val) doing on each iteration when it sets a $key to $val? Can I do that myself?

Maybe I’m not visualizing the idea of an object properly in my mind, but wouldn’t it make more sense for getElementsByTagName and mysql queries to return arrays? Why don’t they?

How to&Answers:

For instance, what exactly is foreach($key as $val) doing on each iteration when it sets a $key to $val? Can I do that myself?

If it really is an array, you can get the first element with reset().

If it’s an Iterator (which is used to allow foreach access to an object) then you should be able to use $object->current();

I’ve never really looked at the underlying code for foreach – however reset() and current() seem analogous to what foreach would ‘do’ at the start of iteration.

Unfortunately, the two examples you reference are internal classes, and according to the docs internal classes (classes that are part of the language or an extension) don’t follow the same rules:

Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

That said, any user classes that return objects that can be iterated by foreach should be of a Traversable type (what foreach requires), so I believe current() should work the way you want. Note that if the object actually implements IteratorAggregate instead of Iterator, you’ll have to use getIterator()->current().

However it’s still possible to do with your two examples – just using methods specific to those returned types. In the case of getElementsByTagName(), you can use getElementsByTagName->item(0) and in the case of PDO you can use query()->fetch().