Zend PHP 7 Certification – Arrays – Objects as Arrays

This post covers the Objects as Arrays section of the Arrays chapter when studying for the Zend PHP 7 Certification.

The ArrayObject class allows objects to work as arrays.

Two constants are available in this class: STD_PROP_LIST and ARRAY_AS_PROPS.

STD_PROP_LIST ensures properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

lt;?php                                                                                                         
$a = new ArrayObject([], ArrayObject::STD_PROP_LIST);
$a['arr'] = 'array data';
$a->prop = 'prop data';
                   
print_r($a);

// Outputs:
                                                    
ArrayObject Object ( 
    [prop] => prop data 
    [storage:ArrayObject:private] => Array (
       [arr] => array data 
    ) 
)

ARRAY_AS_PROPS ensures entries can be accessed as properties (read and write).

<?php
$a = new ArrayObject([], ArrayObject::ARRAY_AS_PROPS);
$a['arr'] = 'array data';
$a->prop = 'prop data';

print_r($a);

// Outputs:

ArrayObject Object ( 
    [storage:ArrayObject:private] => Array (
        [arr] => array data 
        [prop] => prop data 
    ) 
)

The ArrayObject class allows allows for data manipulation by using several of its native methods.

The append method appends a new value as the last element.

<?php
$arrayobj = new ArrayObject(['first','second','third']);
$arrayobj->append('fourth');
$arrayobj->append(['five', 'six']);
var_dump($arrayobj);

// Outputs:
object(ArrayObject)#1 (5) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  string(6) "fourth"
  [4]=>
  array(2) {
    [0]=>
    string(4) "five"
    [1]=>
    string(3) "six"
  }
}

The asort method sorts the entries by value.

<?php
$fruits = ["d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"];
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->asort();

foreach ($fruitArrayObject as $key => $val) {
    echo "$key = $val\n";
}

// Outputs:
c = apple
b = banana
d = lemon
a = orange

The natsort method sorts entries using a natural order algorithm.

<?php
$array = ["d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"];

$arr1 = new ArrayObject($array);
$arr1->natsort();
print_r($arr1);

// Outputs:
c = apple
b = banana
d = lemon
a = orange

View the other sections:

Note: This article is based on PHP version 7.0.