Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an array an instance of Traversable?

Tags:

php

Here is my basic array in my framework

 array(2) {
  [0]=>
  string(2) "40"
  [1]=>
  string(2) "41"
}

Here is my tests:

echo($array instanceof Traversable); // 0
echo(is_array($array)); // 1

It seems my standard php array is not an instance of Traversable which seems inconsistent.

like image 354
c3cris Avatar asked Jul 26 '16 16:07

c3cris


2 Answers

Right, it isn't a Traversable.

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

like image 175
u-nik Avatar answered Oct 31 '22 02:10

u-nik


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
like image 37
barell Avatar answered Oct 31 '22 01:10

barell