A better way to randomly select a key and value pair from an array in PHP

后端 未结 2 883
长情又很酷
长情又很酷 2021-01-16 10:43

As far as I know array_rand() can only grab a radnom array from an array like this:

$array = array( \'apple\', \'orange\', \'banana\' );
$two_ra         


        
相关标签:
2条回答
  • 2021-01-16 11:36

    Just shuffle and slice 2:

    shuffle($array);
    $rand_values = array_slice($array, 0, 2);
    
    0 讨论(0)
  • 2021-01-16 11:38

    First, this line: $rand_values[] .= $array[$key]; is wrong. The .= operator is to join strings, to add a value to the end of the array, you just need $rand_values[] = $array[$key];.

    If you don't care about the keys, just use array_values function to "dump" the keys.

    $array = array('a' => 'orange', 'c' => 'banana', 'b' => 'peach');
    $two_random_items = array_rand(array_values($array) , 2 );
    

    array_values will strip down the keys, and will return an array with the values (the keys will become 0, 1, 2...)

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