Generating a unique sequence of number in PHP

For a project I had to randomize a given sequence of elements. Here’s the code for generate a unique sequence.

 

<?
$originalArray=array();
$randomizedArray=array();
$arraySize=10000;

for ($i=0; $i<$arraySize; $i++){
  array_push($originalArray, $i);
}

//var_dump($originalArray);
for ($i=0; $i<$arraySize; $i++){
$chosenIndex=rand(0, sizeof($originalArray)-1);
echo ‘chosen index: ‘.$chosenIndex.’, Value: ‘;
array_push($randomizedArray, $originalArray[$chosenIndex]);
//unset and update array size
unset($originalArray[$chosenIndex]);
$originalArray=array_values($originalArray);
echo $randomizedArray[$i].'<br>’;
}

?>

Advertisements

One thought on “Generating a unique sequence of number in PHP

  1. Ahoy.

    There are a number of improvements that can be made here.

    If you need to use this approach, you can replace

    $originalArray=array();
    $randomizedArray=array();
    $arraySize=10000;

    for ($i=0; $i<$arraySize; $i++){
    array_push($originalArray, $i);
    }

    with

    $originalArray = range(0, 9999);

    You can then randomize the array with:

    $randomizedArray = $originalArray;
    shuffle($randomizedArray);

    Really, if it's a *unique* number you want, using a function such as uniqid would be better. If you need cryptographically-secure random data, use openssl_random_pseudo_bytes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s