Ruub
Ruub

Reputation: 629

Get a value from array_keys

maybe a simple question but I can't figure it out.. I try to put values from an array in a variable, but it doesn't seem to work.

$array = array(0 => 100, "color" => "red");

print_r(array_keys($array));

Outputs:

Array
(
    [0] => 0
    [1] => color
)

Then why can't I say:

print_r(array_keys($array[1]));

So it will output: color

How do I put color in a variable?

* Update: I work in PHP 5.3, unfortunately

print_r(array_keys($array)[1]);

don't work.

Upvotes: 3

Views: 7769

Answers (3)

h2ooooooo
h2ooooooo

Reputation: 39522

Because $array[1] is the key 1 of $array. If you use PHP 5.4+ you can do this directely:

print_r(array_keys($array)[1]);

DEMO

Otherwise you have to save it a variable first:

$keys = array_keys($array);
print_r($keys[1]);

DEMO

Manual entry for array deferencing in 5.4+:

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

Upvotes: 8

Code Lღver
Code Lღver

Reputation: 15603

because of $array[1] is not an array. it has just a string value.

array_keys functions indentify only the arrays, can not the strings key.

If the $array[1] have an array then it will return an array with values of keys.

Upvotes: 0

Marty
Marty

Reputation: 39458

Did you mean:

print_r(array_keys($array)[1]);
// -----------------------^^^ After array_keys()

Upvotes: 0

Related Questions