Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ArrayIterator, ArrayObject and Array in PHP

Can somebody explain clearly the fundamental differences between ArrayIterator, ArrayObject and Array in PHP in terms of functionality and operation? Thanks!

like image 903
jkhamler Avatar asked May 08 '12 16:05

jkhamler


People also ask

What is array iterator in PHP?

The ArrayIterator class ¶ This iterator allows to unset and modify values and keys while iterating over Arrays and Objects.

What is Arrayobject?

The Array Object. Arrays are data structures that store information in a set of adjacent memory addresses. In practice, this means is that you can store other variables and objects inside an array and can retrieve them from the array by referring to their position number in the array.

What is array of object in PHP?

An object is an instance of a class. It is simply a specimen of a class and has memory allocated. Array is the data structure that stores one or more similar type of values in a single name but associative array is different from a simple PHP array. An array which contains string index is called associative array.

How do you call an array of objects in PHP?

To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.


2 Answers

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 & unseting 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.

like image 94
Mridul Aggarwal Avatar answered Sep 19 '22 13:09

Mridul Aggarwal


ArrayObject and array are somewhat alike. Merely a collection of objects (or native types). They have some different methods that you can call, but it mostly boils down to the same thing.

However, an Iterator is something else completely. The iterator design pattern is a way to secure your array (making it only readable). Lets take the next example:

You have a class that has an array. You can add items to that array by using addSomethingToMyArray. Note however, that we do something to item before we actually add it to the array. This could be anything, but lets for a moment act like it is very important that this method is fired for EVERY item that we want to add to the array.

class A {     private $myArray;     public function returnMyArray()     {         return $this->myArray;     }      public function addSomethingToMyArray( $item )     {         $this->doSomethingToItem( $item );          array_push( $item );     } } 

The problem with this, is that you pass the array by reference here. That means that classes that actually use returnMyArray get the real myArray object. That means that classes other than A can add things to that array, and therefor also change the array inside A without having to use the addSOmethingToMyArray. But we needed to doSOmethingToItem, remember? This is an example of a class not in control of its own inner status.

The solution to this is an iterator. Instead of passing the array, we pass the array to a new object, that can only READ things from the array. The most simple Iterator ever is something like this:

<?php  class MyIterator{      private $array;     private $index;      public function __construct( $array )     {         $this->array = $array;     }      public function hasNext()     {         return count( $this->array ) > $this->index;     }      public function next()     {         $item = $this->array[ $this->index ];         this->$index++;          return $item;     }        } 

?>

As you can see, i have no way of adding new items to the given array, but i do have posibilities to read the array like this:

while( $iterator->hasNext() )     $item = $iterator->next(); 

Now there is again, only one way to add items to myArray in A, namely via the addSomethingToArray method. So that is what an Iterator is, it is somewhat of a shell around arrays, to provide something called encapsulation.

like image 42
David Avatar answered Sep 17 '22 13:09

David