There is an associative array with only one pair key=>value
.
I don't know it's key, but I need to get it's value:
$array = array('???' => 'value'); $value = // ??
$array[0]
doesn't work.
How can I get it's value?
Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
You can also do either of the following functions to get the value since there's only one element in the array.
$value = reset( $array); $value = current( $array); $value = end( $array);
Also, if you want to use array_keys()
, you'd need to do:
$keys = array_keys( $array); echo $array[ $keys[0] ];
To get the value.
As some more options, you can ALSO use array_pop()
or array_shift()
to get the value:
$value = array_pop( $array); $value = array_shift( $array);
Finally, you can use array_values()
to get all the values of the array, then take the first:
$values = array_values( $array); echo $values[0];
Of course, there are lots of other alternatives; some silly, some useful.
$value = pos($array); $value = implode('', $array); $value = current(array_slice($array, 0, 1)); $value = current(array_splice($array, 0, 1)); $value = vsprintf('%s', $array); foreach($array as $value); list(,$value) = each($array);
array_keys()
will get the key for you
$keys = array_keys($array); echo $array[$keys[0]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With