PHP, how to get the Array Key in Single Dimensional Array.
-
05-07-2021 - |
Question
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;
Solution
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)
OTHER TIPS
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));
?>
you need to use array_keys
, here's the manual
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow