views:

67

answers:

4

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
?>
A: 

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']);
zerkms
+1  A: 
$array = array_values($array);

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

kgb
I need the original keys, trying to assign a value to a key which is a string and I have only the number
NoOne
+1  A: 

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
?>
grossvogel
Yeah, it work and its best solve
NoOne
A: 

Solved, thanks for help.

NoOne