Jump to content

Inserting unique random numbers in array


a0101

Recommended Posts

Hello, I want to generate random numbers and insert them into an array.

Here is my code:

<p class="input">Speech ID: <input type="text" readonly value="
<?php
    $arra = array();
for($i = 0; $i < 99999; $i++){
$arra($i) = rand(100000, 999999);
}
    $speechidarr = array_unique($arra);
    foreach ($speechidarr as $speechID) {
echo $speechID;
?> />

My code gets a fatal error apparently:

Fatal error: Can't use function return value in write context

For small ranges, this is probably the simplest code possible

 

<?php

$start = 1; $end = 100; $pick = 10;

$range = range($start,$end);
shuffle($range);

$numbers = array();

for($i = 0; $i < $pick; $i++ )
$numbers[] = $range[$i];

print_r($numbers);

?>

 

This becomes a bad idea when using large ranges though, because you have to create an array containing that many values, which becomes memory heavy. For that, I'd use the more complex code below

 

<?php

$start = 1; $end = 1000000; $pick = 10;

$numbers = array();

for($i = 0; $i < $pick; $i++ ) {
// Generate a random number
$random = mt_rand($start, $end);
// Check to see if numbers been used
if( isset($numbers[$random]) )
	// If it has, subtract i by 1, 're-doing' the current loop
	$i--;
// Else, the number hasn't been used
else
	// Set the key to the number, and give it some value
	$numbers[$random] = false;
}
// We use the array's key, rather than it's value to store the number
// That's because using in_array() is MUCH slower than isset(). Since
// isset checks the key, and there's no overhead added, we use that.
// We then grab all the keys, and replace them with a new array of them as values
$numbers = array_keys($numbers);

print_r($numbers);

?>

 

Hope this helps.

 

Edit - You were using round brackets () instead of square ones [] for your arrays.

If you need to use all 10000 numbers, and they need to be unique, you don't really have a choice but to store them in an array :)

 

Keep in mind, setting a $pick to a value greater than $end - $start will result in an infinite loop.

 

If you're grabbing a large percentage of the values, my first example is better... here's an improved example.

 

<?php

$start = 1; $end = 1000; $pick = 750;

$range = range($start,$end);
shuffle($range);

$numbers = array_slice($range, 0, $pick);

print_r($numbers);	

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.