Skip to content

Instantly share code, notes, and snippets.

@vrana

vrana/AnyKeyArray.php

Last active Dec 17, 2015
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@o5 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

This comment has been minimized.

Copy link

@dg 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