Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Jul 2004
    Posts
    134
    Thanks
    0
    Thanked 0 Times in 0 Posts

    5 unique random number in an array

    I've wrote this code

    $max = 9;
    for($i=0; count($random)<5; $i++) {
    $random[$i]=rand(1, $max);
    for($j=0; $j<count($random); $j++) {
    if($random[$i]==$random[$j]) {
    $random[$i]==NULL;
    array_pop($random);
    }
    }
    }

    while(list($key, $value) = each($random))
    echo $value . ", ";

    Sometimes, I get repeated numbers; please help me, where I've mistaken.
    ghost

  • #2
    Regular Coder
    Join Date
    May 2005
    Posts
    563
    Thanks
    0
    Thanked 3 Times in 3 Posts
    PHP Code:
    $max 9;
    for(
    $i=0;count($random)<5$i++) {
        
    $rand=rand(1$max);
        if(!
    in_array($rand,$random)) {
            
    $random[$i]=$rand;
        }

    The repeated numbers came from you not actually comparing them, you used == instead of = which is a compare operation. It was basically the same as having
    PHP Code:
    true
    written on a line by itself.

    Also, use php functions where possible rather than doing it yourself.
    Last edited by SeeIT Solutions; 06-16-2005 at 07:43 AM.

  • #3
    Regular Coder
    Join Date
    Jul 2004
    Posts
    134
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanx, that worked but as indexes of array is not sequential; I added
    Code:
    while(list($key, $value) = each($random))
    	$random_[] = $value;
    Isn't PHP has a function for this also?

    guideseeq IT Workz

  • #4
    Regular Coder
    Join Date
    Feb 2005
    Location
    West Midlands, UK
    Posts
    623
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You mean you want to turn something like this:

    Code:
    Array
    (
        [0] => 7
        [2] => 3
        [5] => 2
        [6] => 6
        [12] => 4
    )
    into this:
    Code:
    Array
    (
        [0] => 7
        [1] => 3
        [2] => 2
        [3] => 6
        [4] => 4
    )
    If so, you can use the array_values() function:
    PHP Code:
    $random array_values($random); 

  • #5
    Regular Coder
    Join Date
    Jul 2004
    Posts
    134
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes. Excellent PHP functions Thank you both


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •