NoOne
NoOne

Reputation: 33

Array key as string and number

How to make arrays in which the key is number and string.

<?php
$array = array
(
    'test' => 'thing',
    'blah' => 'things'
);

echo $array[0]; // thing
echo $array[1]; // things

echo $array['test']; // thing
echo $array['blah']; // things
?>

Upvotes: 3

Views: 6272

Answers (3)

grossvogel
grossvogel

Reputation: 6782

You could use array_keys to generate a lookup array:

<?php
$array = array
(
    'test' => 'thing',
    'blah' => 'things'
);
$lookup = array_keys ($array);
// $lookup holds (0=>'test',1=>'blah)

echo $array[$lookup[0]]; // thing
echo $array[$lookup[1]]; // things

echo $array['test']; // thing
echo $array['blah']; // things
?>

Upvotes: 2

zerkms
zerkms

Reputation: 254886

You could implement your own class that "implements ArrayAccess"

For such class you can manually handle such behaviour

UPD: implemented just for fun

class MyArray implements ArrayAccess
{
    private $data;
    private $keys;

    public function __construct(array $data)
    {
        $this->data = $data;
        $this->keys = array_keys($data);
    }

    public function offsetGet($key)
    {
        if (is_int($key))
        {
            return $this->data[$this->keys[$key]];
        }

        return $this->data[$key];
    }

    public function offsetSet($key, $value)
    {
        throw new Exception('Not implemented');
    }

    public function offsetExists($key)
    {
        throw new Exception('Not implemented');
    }

    public function offsetUnset($key)
    {
        throw new Exception('Not implemented');
    }
}

$array = new MyArray(array(
    'test' => 'thing',
    'blah' => 'things'
));

var_dump($array[0]);
var_dump($array[1]);
var_dump($array['test']);
var_dump($array['blah']);

Upvotes: 1

Sergey Eremin
Sergey Eremin

Reputation: 11080

$array = array_values($array);

but why would you need that? can you extend your example?

Upvotes: 2

Related Questions