- Accessing All Elements of Numeric Arrays
- Accessing All Elements of Associative Arrays
- Accessing All Array Elements in Nested Arrays
- Turning an Array into Variables
- Converting Strings to Arrays
- Converting Arrays to Strings
- Sorting Arrays Alphabetically
- Sorting Associative Arrays Alphabetically
- Sorting Nested Arrays
- Sorting Nested Associative Arrays
- Sorting IP Addresses (as a Human Would)
- Sorting Anything
- Sorting with Foreign Languages
- Applying an Effect to All Array Elements
- Filtering Arrays
- Getting Random Elements Out of Arrays
- Making Objects Behave Like Arrays
Making Objects Behave Like Arrays
class MyArray implements ArrayAccess, Countable
<?php class MyArray implements ArrayAccess, Countable { private $_data = array(); /* ArrayAccess interface */ public function offsetSet($offset, $value) { $this->_data[$offset] = $value; } public function offsetExists($offset) { return isset($this->_data[$offset]); } public function offsetUnset($offset) { unset($this->_data[$offset]); } public function offsetGet($offset) { //return (isset($this->_data[$offset])) ? $this->_data[$offset] : null; return ($this->offsetExists($offset)) ? $this->_data[$offset] : null; } /* Countable Interface */ public function count() { return count($this->_data); } } $a = new MyArray(); $a[0] = 'I'; $a[1] = 'II'; $a[2] = 'III'; $a[3] = 'IV'; for ($i = 0; $i < count($a); $i++) { printf('<p>%s</p>', htmlspecialchars($a[$i])); } ?>
Using an Object Like an Array with SPL (splArray.php)
SPL, the Standard PHP Library, is one of the most underrated features of PHP. It basically offers a huge set of interfaces. If you create a class using one of those interfaces, you might use standard PHP functions with your class. The documentation at http://php.net/spl is not always as detailed as you would expect, but it does give you some great pointers as to what is possible.
As a simple example, we will create a class (you can find more about various aspects of object-oriented programming [OOP] in Chapter 4) that implements two interfaces:
- ArrayAccess—Allows accessing individual elements within the object’s collection (in our code, a simple array)
- Countable—Allows calling count() on an object instance
If you want full array support, you need to implement additional interfaces, including Iterable (for iterator support; for example, via foreach) and some more. The ArrayObject interface aggregates several of the required interfaces, which in turn could even allow advanced features like user-defined sorting.