Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value without knowing key in one-pair-associative-array

Tags:

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?

like image 207
Qiao Avatar asked Jun 21 '12 19:06

Qiao


People also ask

How do you find the key of an associative array?

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.

Does in_array work for 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.

Can associative array have same key?

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.

What is the use of in_array ()?

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.


2 Answers

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); 
like image 95
nickb Avatar answered Oct 06 '22 01:10

nickb


array_keys() will get the key for you

$keys = array_keys($array); echo $array[$keys[0]]; 
like image 43
John Conde Avatar answered Oct 06 '22 01:10

John Conde