3

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
?>
3
  • your question is not clear, what exactly do you want/mean? Commented Jun 27, 2010 at 15:00
  • That won't work reliably. The order of the items in an assoziative array is not depending on the order in which they are entered. The first element in the array might as well be blah instead of test. Commented Jun 27, 2010 at 15:09
  • @dbemerlin: Do you have a reference supporting your comment? I've always thought associative arrays were ordered according to the order of insertion, but I can't find anything in the manual that says one way or another. Commented Jun 27, 2010 at 15:30

3 Answers 3

2
$array = array_values($array);

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

Sign up to request clarification or add additional context in comments.

1 Comment

I need the original keys, trying to assign a value to a key which is a string and I have only the number
2

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

Comments

1

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']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.