How to select N unique random indices from an existing array in PHP

1 Answer

0 votes
/*
    Select N unique random indices from an existing array in PHP.
    Return the indices and print both the index and the corresponding value.

    Approach:
    - Build an array of indices: 0, 1, 2, ..., size-1.
    - Shuffle the indices using shuffle() (Fisher–Yates internally).
    - Take the first N shuffled indices — guaranteed unique.
    - Return those indices to the caller.
*/

/* Return N unique random indices */
function pick_unique_indices(int $arraySize, int $count): array
{
    if ($count > $arraySize) {
        throw new InvalidArgumentException(
            "Cannot pick more unique indices than array size."
        );
    }

    // Build index list
    $indices = range(0, $arraySize - 1);

    // Shuffle indices
    shuffle($indices);

    // Return first N indices
    return array_slice($indices, 0, $count);
}

/* Main program */

// Example array
$data = [5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6];

$N = 6; // number of unique indices to pick

// Get unique random indices
$indices = pick_unique_indices(count($data), $N);

// Print results
echo "Random unique indices and their values:\n";
foreach ($indices as $idx) {
    echo "index $idx -> value {$data[$idx]}\n";
}


/*
run:

Random unique indices and their values:
index 10 -> value 17
index 3 -> value 19
index 16 -> value 6
index 4 -> value 5
index 9 -> value 61
index 8 -> value 58

*/

 



answered Sep 12 by avibootz

Related questions

...