Last active
December 17, 2015 08:39
-
-
Save vrana/5581788 to your computer and use it in GitHub Desktop.
Array-like object allowing any serializable keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class AnyKeyArray implements ArrayAccess, Iterator, Countable { | |
private $values = array(); | |
// ArrayAccess | |
function offsetSet($key, $value) { | |
$this->values[serialize($key)] = $value; | |
} | |
function offsetGet($key) { | |
return $this->values[serialize($key)]; | |
} | |
function offsetExists($key) { | |
return array_key_exists(serialize($key), $this->values); | |
} | |
function offsetUnset($key) { | |
unset($this->values[serialize($key)]); | |
} | |
// Iterator | |
function rewind() { | |
reset($this->values); | |
} | |
function valid() { | |
return (key($this->values) !== null); | |
} | |
function current() { | |
return current($this->values); | |
} | |
function key() { | |
return unserialize(key($this->values)); | |
} | |
function next() { | |
next($this->values); | |
} | |
// Countable | |
function count() { | |
return count($this->values); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The strange thing is that you cannot use foreach to iterate over array with special keys. I found it when I read the changelog for PHP 5.5.