How to get a random value from 1~N but excluding several specific values in PHP?

前端 未结 7 2017
不知归路
不知归路 2020-12-10 06:56

rand(1,N) but excluding array(a,b,c,..),

is there already a built-in function that I don\'t know or do I have to implement it myself(how?)

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 07:26

    Maybe its too late for answer, but I found this piece of code somewhere in my mind when trying to get random data from Database based on random ID excluding some number.

    $excludedData = array(); // This is your excluded number
    $maxVal = $this->db->count_all_results("game_pertanyaan"); // Get the maximum number based on my database
    
    $randomNum = rand(1, $maxVal); // Make first initiation, I think you can put this directly in the while > in_array paramater, seems working as well, it's up to you
    while (in_array($randomNum, $excludedData)) {
      $randomNum = rand(1, $maxVal);
    }
    
    $randomNum; //Your random number excluding some number you choose

提交回复
热议问题