10

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.

c3cris
  • 1,276
  • 2
  • 15
  • 37
  • Arrays do not implement `Traversable` in PHP but they will be traversable in `foreach` – Aaron Jul 26 '16 at 16:27
  • An array is not a class, so it also isn't even capable of extending from any class or interface. Traversable is for things like iterators and such. – Rizier123 Jul 26 '16 at 16:28
  • 3
    As of PHP 7.1, you can use the pseudo-type `iterable` as a type declaration, which allows use of arrays or something implementing Traversable: http://php.net/manual/en/language.types.iterable.php – still_dreaming_1 Aug 25 '17 at 02:15

3 Answers3

15

Right, it isn't a Traversable.

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

mmabdelgawad
  • 2,385
  • 2
  • 7
  • 15
u-nik
  • 488
  • 4
  • 12
6
  • Arrays in php are primitive types and primitives cannot inherit from classes or implement interfaces

  • Therefore the array type in php is not an instance of Traversable

What I want to add as additional info is:

  • that array and Traversable combined form another type called iterable
  • In other words the iterable type in php is the union of Traversable | array
  • Interface types like iterator and generator implement Traversable and therefore are of type iterable
  • This is usually helpful if you implement a function which takes as an argument which we want to iterate over (using foreach) but we don't know beforehand if it will be an array or another iterable data structure (like a class which implements Iterator).
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
4

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
barell
  • 1,470
  • 13
  • 19