Is an array an instance of Traversable?

Whether it is consistent or not, array is just a primitive type in php (not a class) so it won't follow object oriented style of implementing interfaces - in this case Traversable interface.

However, PHP gives us a nice way to convert array into object with \ArrayObject which will behave almost like an array (almost because it's actually an object not an array):

$someArray = ['foo' => 'bar'];
$objectArray = new \ArrayObject($someArray);

// now you can use $objectArray as you would your $someArray:

// access values
$objectArray['foo']

// add values
$objectArray['boo'] = 'far';

// foreach it
foreach ($objectArray as $key => $value) { ... }

// it also implements \Traversable interface!
$objectArray instanceof \Traversable // true

Right, it isn't a Traversable.

The main goal of the interface Traversable is to make objects usable with foreach.

Tags:

Php