Skip to content

Instantly share code, notes, and snippets.

@vrana
Last active December 17, 2015 08:39
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrana/5581788 to your computer and use it in GitHub Desktop.
Save vrana/5581788 to your computer and use it in GitHub Desktop.
Array-like object allowing any serializable keys
<?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);
}
}
@o5
Copy link

o5 commented May 16, 2013

Jakube, nemělo by tady být raději isset() ? Rád bych v tom měl konečně jasno, viz...

@dg
Copy link

dg commented May 16, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment