Can somebody explain clearly the fundamental differences between ArrayIterator
, ArrayObject
and Array
in PHP in terms of functionality and
Array
is a native php type. You can create one using the php language construct array()
, or as of php 5.4 onwards []
ArrayObject
is an object
that work exactly like arrays. These can be created using new
keyword
ArrayIterator
is like ArrayObject
but it can iterate on itself. Also created using new
Comparing Array
vs (ArrayObject
/ArrayIterator
)
They both can be used using the php's array syntax, for eg.
$array[] = 'foo';
$object[] = 'foo';
// adds new element with the expected numeric key
$array['bar'] = 'foo';
$object['bar'] = 'foo';
// adds new element with the key "bar"
foreach($array as $value);
foreach($object as $value);
// iterating over the elements
However, they are still objects vs arrays, so you would notice the differences in
is_array($array); // true
is_array($object); // false
is_object($array); // false
is_object($object); // true
Most of the php array functions expect arrays, so using objects there would throw errors. There are many such functions. For eg.
sort($array); // works as expected
sort($object); // Warning: sort() expects parameter 1 to be array, object given in ......
Finally, objects can do what you would expect from a stdClass
object, i.e. accessing public properties using the object syntax
$object->foo = 'bar'; // works
$array->foo = 'bar'; // Warning: Attempt to assign property of non-object in ....
Arrays (being the native type) are much faster than objects. On the other side, the ArrayObject
& ArrayIterator
classes have certain methods defined that you can use, while there is no such thing for arrays
Comparing ArrayObject
vs ArrayIterator
The main difference between these 2 is in the methods the classes have.
The ArrayIterator
implements Iterator
interface which gives it methods related to iteration/looping over the elements. ArrayObject
has a method called exchangeArray
that swaps it's internal array with another one. Implementing a similar thing in ArrayIterator
would mean either creating a new object or looping through the keys & unset
ing all of them one by one & then setting the elements from new array one-by-one.
Next, since the ArrayObject
cannot be iterated, when you use it in foreach
it creates an ArrayIterator
object internally(same as arrays). This means php creates a copy of the original data & there are now 2 objects with same contents. This will prove to be inefficient for large arrays. However, you can specify which class to use for iterator, so you can have custom iterators in your code.
Hope this is helpful. Edits to this answer are welcome.