get random value from a PHP array, but make it unique

后端 未结 9 1066
挽巷
挽巷 2020-12-16 19:44

I want to select a random value from a array, but keep it unique as long as possible.

For example if I\'m selecting a value 4 times from a array of 4 elements, the s

相关标签:
9条回答
  • 2020-12-16 20:38

    You almost have it right. The problem was the unset($arr_history[$selected]); line. The value of $selected isn't a key but in fact a value so the unset wouldn't work.

    To keep it the same as what you have up there:

    <?php
    
    $arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');
    
    for ( $i = 1; $i < 10; $i++ )
    {
      // If the history array is empty, re-populate it.
      if ( empty($arr_history) )
        $arr_history = $arr;
    
      // Select a random key.
      $key = array_rand($arr_history, 1);
    
      // Save the record in $selected.
      $selected = $arr_history[$key];
    
      // Remove the key/pair from the array.
      unset($arr_history[$key]);
    
      // Echo the selected value.
      echo $selected . PHP_EOL;
    }
    

    Or an example with a few less lines:

    <?php
    
    $arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');
    
    for ( $i = 1; $i < 10; $i++ )
    {
      // If the history array is empty, re-populate it.
      if ( empty($arr_history) )
        $arr_history = $arr;
    
      // Randomize the array.
      array_rand($arr_history);
    
      // Select the last value from the array.
      $selected = array_pop($arr_history);
    
      // Echo the selected value.
      echo $selected . PHP_EOL;
    }
    
    0 讨论(0)
  • 2020-12-16 20:38

    key != value, use this:

    $index = array_rand($arr_history, 1);
    $selected = $arr_history[$index];  
    unset($arr_history[$index]); 
    
    0 讨论(0)
  • 2020-12-16 20:38

    I've done this to create a random 8 digit password for users:

    $characters = array(
        "A","B","C","D","E","F","G","H","J","K","L","M",
        "N","P","Q","R","S","T","U","V","W","X","Y","Z",
        "a","b","c","d","e","f","g","h","i","j","k","m",
        "n","p","q","r","s","t","u","v","w","x","y","z",
        "1","2","3","4","5","6","7","8","9");
    
    for( $i=0;$i<=8;++$i ){
        shuffle( $characters );
        $new_pass .= $characters[0];
    }
    
    0 讨论(0)
提交回复
热议问题