Selecting a random element from a PHP associative array

后端 未结 3 1262
余生分开走
余生分开走 2020-12-15 06:08

I\'ve got an associative array in PHP and want to select a random key/value pair out of it. Here\'s what I have so far:

Initialize.

$locations = arra         


        
相关标签:
3条回答
  • 2020-12-15 06:41

    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

    0 讨论(0)
  • 2020-12-15 06:52
    $array = array('a' => 1, 'b' => 2);
    $key = array_rand($array);
    $value = $array[$key];
    
    0 讨论(0)
  • 2020-12-15 06:55

    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.

    0 讨论(0)
提交回复
热议问题