Skip to content
Advertisement

How to generate a random number array and sorting this array using php?

I want to generate 5 random number array and shorting this array using php like the image.

I am using this code that generate 1 array.

<?php

$array=array();
$array_temp=array();
$found=0;

while($found!=5):         
    $v=rand(1,20);               
    if(!in_array($v,$array)):   
        $array[]=$v;
        $array_temp[]=$v;            
        $found++;               
    endif;
endwhile;
print_r($array_temp);

for($j = 0; $j < count($array); $j ++) {
    for($i = 0; $i < count($array)-1; $i ++){

        if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }       
    }
}
print_r($array);

?>

Advertisement

Answer

Use this code and take a look at my comments within the code:

// Generate array having 20 numbers from 1 to 20
$range = range(1, 20);
// Change the order of elements
shuffle($range);
// Split array into 4 chunks each having 5 elements
$unsorted = array_chunk($range, 4);
// Copy original array
$sorted = $unsorted;
// Sort copied array
array_walk($sorted, 'sort');

Now you have 2 arrays having same elements, but one array is sorted:

print_r($unsorted);

// prints:
Array
(
    [0] => Array
        (
            [0] => 14
            [1] => 10
            [2] => 3
            [3] => 9
        )

    [1] => Array
        (
            [0] => 8
            [1] => 7
            [2] => 19
            [3] => 16
        )

    [2] => Array
        (
            [0] => 11
            [1] => 20
            [2] => 5
            [3] => 12
        )

    [3] => Array
        (
            [0] => 15
            [1] => 4
            [2] => 2
            [3] => 18
        )

    [4] => Array
        (
            [0] => 17
            [1] => 6
            [2] => 1
            [3] => 13
        )

)

print_r($sorted);

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 9
            [2] => 10
            [3] => 14
        )

    [1] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 16
            [3] => 19
        )

    [2] => Array
        (
            [0] => 11
            [1] => 12
            [2] => 20
            [3] => 5
        )

    [3] => Array
        (
            [0] => 2
            [1] => 4
            [2] => 15
            [3] => 18
        )

    [4] => Array
        (
            [0] => 1
            [1] => 6
            [2] => 13
            [3] => 17
        )

)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement