ArrayObject
ArrayObject wraps a plain array in an object that can sort, swap and read its own contents. A program can pull the plain array back out when it needs one.
ksort orders the wrapped array
The object here wraps the keys b and a out of order. ksort sorts by key, and print_r of the copy shows a first.
<?php
$obj = new ArrayObject(["b" => 2, "a" => 1]);
$obj->ksort();
print_r($obj->getArrayCopy());exchangeArray swaps the whole contents
The object here starts with a name and a city. exchangeArray replaces both pairs at once, and the copy shows only the new pairs.
<?php
$obj = new ArrayObject(["name" => "Hana", "city" => "Oslo"]);
$obj->exchangeArray(["theme" => "dark", "lang" => "en"]);
print_r($obj->getArrayCopy());Count and read one value by key
count counts the two wrapped pairs here. offsetGet reads the value stored under the city key.
<?php
$obj = new ArrayObject(["name" => "Hana", "city" => "Oslo"]);
echo count($obj) . "\n";
echo $obj->offsetGet("city") . "\n";Example
<?php
$settings = new ArrayObject(["volume" => 7, "theme" => "dark", "lang" => "en"]);
$settings->ksort();
print_r($settings->getArrayCopy());
echo "Theme: " . $settings->offsetGet("theme") . "\n";Key points
- ArrayObject wraps a plain array in an object.
- Use ksort to sort the wrapped array by its keys.
- Use getArrayCopy to read the wrapped values as a plain array.
- Use exchangeArray to swap the whole wrapped array for a new one.
- count counts the values held in the object.
- Use offsetGet to read one value by its key.
In this example, the settings object wraps three pairs with keys out of order. ksort sorts the pairs by key, and the copy prints lang, theme and volume in that order. offsetGet then reads the theme value on its own line.
Note
ArrayObject has no sort method, so its ordering methods carry names like ksort and asort.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method swaps the whole contents of an ArrayObject for a new array?