Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
318 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...