Question

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

Was it helpful?

Solution

i noticed you mentioned it is a readonly database result set

if you are using mysql then you could do something like this

$result = mysql_query($sql);
$data = mysql_fetch_array($result);

mysql_fetch_array returns an array with both associative and numeric keys

http://nz.php.net/manual/en/function.mysql-fetch-array.php

OTHER TIPS

how about this 

$data = array(
    'one' => 'something', 
    'two' => 'else', 
    'three' => 'completely'
) ;

then 
$keys = array_keys($data);

Then 
$key = $keys[$index_you_want];

Then 
echo $data[$key];

There isn't a built-in way to do this.

If it's a one-off thing you could use something like:

$array = array_merge($array, array_values($array));

This won't update as you add new items to the array though.

Sometimes it's easier to check if you have an associative key or an index with is_int()

if(is_int($key))
    return current(array_slice($data, $key, 1));
else
    return $data[$key];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top