質問

I'm new to php so please take it easy.

I have created an array of integers. 1-100. What I want to do is shuffle the array and remove random numbers from it leaving only lets say 15 numbers.

This is what I have done so far, can't figure out how to remove the random numbers. I know I could possibly use unset function but I'm unsure how could I use it in my situation.

// Create an Array using range() function
    $element = range(1, 100);

    // Shuffling $element array randomly
    shuffle($element);

    // Set amount of number to get rid of from array
    $numbersOut = 85;

    // Remove unnecessary items from the array
    var_dump($element);
役に立ちましたか?

解決

Just try with:

$element = range(1, 100);
shuffle($element);
$output = array_slice($element, 0, 15);

var_dump($output);

Output:

array (size=15)
  0 => int 78
  1 => int 40
  2 => int 10
  3 => int 94
  4 => int 82
  5 => int 16
  6 => int 15
  7 => int 57
  8 => int 79
  9 => int 83
  10 => int 32
  11 => int 13
  12 => int 96
  13 => int 48
  14 => int 62

Or if you want to use $numbersOut variable:

$numbersOut = 85;
$output = array_slice($element, $numbersOut);

It will slice an array from 85 to the end. Remember - if you will have 90 elements in the array, this method will return just 5 elements.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top