Effizient zufällige Elemente aus großem PHP Array ziehen

Leider ist der Eintrag nur auf Amerikanisches Englisch verfügbar.

2 Replies to “Effizient zufällige Elemente aus großem PHP Array ziehen”

  1. Maybe i am wrong, but i think that call count() in a while-loop is a performance loss because it will be called in each loop? Additionally, count() on the $array will be executed at least twice (the second one in the mt_rand()-line).

    So i think that this would be better:


    $arrayLength = count($array);
    $randomArray = [];
    while ($arrayLength < $k) {
    $randomKey = mt_rand(0, $arrayLength - 1);
    $randomArray[$randomKey] = $array[$randomKey];
    }

    1. I thought it would not make much difference but you are right, with $arrayLength = count($array) and using that in mt_rand we can even improve the results a bit more. However, don’t use $arrayLength in the while-condition, there we need to check the size of the result array.

Comments are closed.