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)

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
Oli Comber
  • 311
  • 2
  • 11

2 Answers2

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 1
    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. – Oli Comber Feb 13 '14 at 10:48
  • @OliComber: That would be definitely nice, but frankly it would be such a major change that I really can't see it happening. – Jon Feb 13 '14 at 11:02
0

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

pjabang
  • 199
  • 1
  • 2
  • 3
    Careful, casting might lead to unexpected results (when especially when casting an object that inherits from other classes) – Elias Van Ootegem Sep 06 '13 at 11:39
  • 1
    In case you're interested [here's more details on casting objects to arrays](http://stackoverflow.com/questions/17695490/cast-object-to-array-strange-behaviour/17695596#17695596). Also test this with nested objects... casts are not recursive! – Elias Van Ootegem Sep 06 '13 at 11:55