How can I make ArrayIterator or ArrayObject work with implode?
Asked Answered
S

2

8

I'm having a few problems with ArrayIterator (And, indeed, the same problem with ArrayObject).

For 99% of everything, my extended ArrayIterator behaves like an array and is working great.

Unfortunately, implode() does not like being given an ArrayIterator (or ArrayObject).

I can't spot in the docs anywhere which suggests any other classes to implement on by extended ArrayIterator, nor any other methods to override.

Can anyone suggest how to get this working? (Note: Casting to an array every time I use implode is not a solution, as I'd like this array-like object to work EXACTLY as an array, and not have the code using it to have to know/care/cast)

Separatist answered 6/9, 2013 at 11:33 Comment(0)
T
10

The easiest correct solution is to use iterator_to_array to feed implode, e.g.

$traversable = /* your iterator, ArrayObject or any other type of Traversable */
echo implode(",", iterator_to_array($traversable));

This will work as expected with anything that can be iterated with foreach.

Twohanded answered 6/9, 2013 at 11:40 Comment(2)
Thanks Jon. I'm going to set this as the accepted answer because it is a useful function which I didn't know. However, this does require that the callee knows it is not dealing with an array and casts it. It is slow, requires extra code, and offends any ideas of black boxing one might have. Hopefully the PHP devs will one day make all array functions accept objects descended from the Array class, or a common base that Array and similar share.Separatist
@OliComber: That would be definitely nice, but frankly it would be such a major change that I really can't see it happening.Twohanded
M
0

try downcasting the array ((array) $arrayObject) : implode(",", (array) $arrayObject);

Mimamsa answered 6/9, 2013 at 11:38 Comment(2)
Careful, casting might lead to unexpected results (when especially when casting an object that inherits from other classes)Sweeping
In case you're interested here's more details on casting objects to arrays. Also test this with nested objects... casts are not recursive!Sweeping

© 2022 - 2024 — McMap. All rights reserved.