ngplayground
ngplayground

Reputation: 21617

PHP get key value from array

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.

Upvotes: 0

Views: 123

Answers (3)

Daniel Gasser
Daniel Gasser

Reputation: 5133

Use array_keys():

var_dump(array_keys($data));

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

Upvotes: 4

yukisan
yukisan

Reputation: 21

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; 

Upvotes: 0

user2923827
user2923827

Reputation:

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

Upvotes: 0

Related Questions