1

When I put print_r($data); I get the following

Array
(
    [name] => Cheese
)

Is there a way to get the key name in a variable on its own?

There may be occasions that name could be email and other values.

3
  • key() or list($key, $val) = each($data); Commented Sep 17, 2015 at 21:59
  • 3
    expect more from people with 3k rep , just saying. Commented Sep 17, 2015 at 22:01
  • Maybe he's just messing? Lol Commented Sep 17, 2015 at 22:08

3 Answers 3

5

Use array_keys():

var_dump(array_keys($data));

Return all the keys or a subset of the keys of an array

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

Comments

0

Do you mean you know the value but you don't know the key? If so you could write something like this:

$array = ['name' => 'Cheese'];
array_flip($array);
var_export($array['Cheese']); // Output: name

Comments

0

You can have the array key extracted to their own variables using the extract function. For example

$a = array("color"=>"blue");
extract($a);
echo $color; 

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.