In PHP I create an array of key value pairs like this, how to I get "mykey"?
$arr = array("mykey"=>"myvalue");
I know the code below will work, but I am interested to know if there is a language construct in PHP that allows me to this in a easier fashion.
foreach($arr as $key=>$value){
$result = $key;
break;
}
echo $result;
Just Use key if you dealing with one element and array_keys with arrays with multiple values.
Example
$arr = array("mykey"=>"myvalue");
var_dump(key($arr));
Or
var_dump(array_keys($arr));
Output
string 'mykey' (length=5)
and
array
0 => string 'mykey' (length=5)
try this
you can use array_keys function in php
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
您需要使用array_keys
,这是手册
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.