简体   繁体   中英

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.

Use array_keys() :

var_dump(array_keys($data));

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

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

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM