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.
Right, it isn't a Traversable.
The main goal of the interface Traversable is to make objects usable with foreach
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With