I have an associative array that I might need to access numerically (ie get the 5th key's value).
$data = array( 'one' => 'something', 'two' => 'else', 'three' => 'completely' ) ; I need to be able to do:
$data['one'] and
$data[0] to get the same value, 'something'.
My initial thought is to create a class wrapper that implements ArrayAccess with offsetGet() having code to see if the key is numeric and act accordingly, using array_values:
class MixedArray implements ArrayAccess { protected $_array = array(); public function __construct($data) { $this->_array = $data; } public function offsetExists($offset) { return isset($this->_array[$offset]); } public function offsetGet($offset) { if (is_numeric($offset) || !isset($this->_array[$offset])) { $values = array_values($this->_array) ; if (!isset($values[$offset])) { return false ; } return $values[$offset] ; } return $this->_array[$offset]; } public function offsetSet($offset, $value) { return $this->_array[$offset] = $value; } public function offsetUnset($offset) { unset($this->_array[$offset]); } } I am wondering if there isn't any built in way in PHP to do this. I'd much rather use native functions, but so far I haven't seen anything that does this.
Any ideas?
Thanks,
Fanis