1

I would think this would be easier to find but I've been scouring google with no luck. Can you create an array with both a numbered and named index? I know it has to be possible because mysqli_fetch_array returns one, but I can't find any reference to it. Thanks.

1
  • 2
    To access a 'named' index, associative array via an integer: $keys = array_keys($my_arr); $my_arr[$keys[1]] = "element_value"; [1] being the integer. This requires less memory than storing an array with both an integer and named element, plus it makes manipulation/editing simple. Commented Jul 24, 2014 at 14:27

3 Answers 3

4

As per official documentation:

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

The key can either be an integer or a string. The value can be of any type.

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

Comments

0

Nothing to it:

$x = array();
$x['foo'] = 'bar';
$x[1] = 'baz';

Use any key you want. As long as whatever you're using for a key is an int or a valid string, it can be a key.

Comments

0

Yes. PHP arrays can have mixed keys (strings and integers). A reference to it can be found in the docs here: http://php.net/manual/en/language.types.array.php.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Check Example #3:

<?php
    $array = array(
        "foo" => "bar",
        "bar" => "foo",
        100   => -100,
        -100  => 100,
    );
    var_dump($array);
?>

outputs:

array(4) {
    ["foo"] => string(3) "bar"
    ["bar"] => string(3) "foo"
    [100] => int(-100)
    [-100] => int(100)
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.