3

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.

3 Answers 3

8

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.

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

4 Comments

It's a string, so instead of print_r(), you can echo it :)
@AmalMurali You're right - this was only to copy OP's way of doing it. :) I feel that the less we change in our answers, the more the OP understands the change.
@Ruub Can you update your OP with the second example? You can't use the first way, as that requires 5.4+.
@Ruub Your second piece of code should work perfectly, and if it doesn't you've probably done something wrong somewhere else in your code. As shown here it works fine. If you copy paste that code, it works fine, right? Can you create an example on 3v4l, codepad, etc., where the second example fails with your code?
0

Did you mean:

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

Comments

0

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.

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.