Selecting a random element from a PHP associative array

佐手、 提交于 2019-11-29 01:25:47
$array = array('a' => 1, 'b' => 2);
$key = array_rand($array);
$value = $array[$key];

array_rand() returns a key from the array, not a value. You can just use:

$location_name = $locations[$rand];

To get the location name.


Here's a full example: http://codepad.org/zR2YdMGN

Just click submit a few times, you'll see the random working.

your push is wrong

$locations[$location_id] = $location_name;

it should be

so, there is nothing about selecting random element in your question.
always debug your code, just to see if you have proper data before using it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!