1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

$random = rand(0,10);

Discussion in 'PHP' started by pixmania, Jul 21, 2009.

  1. #1
    $random = rand(0,10);
    
    if (($random > 0) && ($random < 5)) { 
    some function
    } 
    
    if (($random > 5) && ($random < 7)) { 
    some function
    } 
    
    if (($random > 7) && ($random < 11)) { 
    some function 
    } 
    
    echo $random; 
    PHP:
    If 0,5 or 7 come out, my function for that number wont function, does anybody know what I'm doing wrong ?

    Would I better of writing 10 functions ?

    if ($random_number == 1) { some function }
    elseif ($random_number == 2) { some function}
    elseif ($random_number == 3) { some function}
    elseif ($random_number == 4) { some function}

    etc...
     
    pixmania, Jul 21, 2009 IP
  2. darkmessiah

    darkmessiah Peon

    Messages:
    500
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #2
    you need to put in a >= or <= somewhere. You are making it so those numbers are never picked.
     
    darkmessiah, Jul 21, 2009 IP
  3. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #3
    Using the equal sign like this

    
    $random = rand(0,10);
    
    if (($random >= 0) && ($random < 5)) { 
    //0 to 4
    } 
    
    if (($random >= 5) && ($random < 7)) { 
    //5 to 6
    } 
    
    if (($random >= 7) && ($random < 11)) { 
    //7 to 10
    } 
    
    echo $random;
    
    PHP:
     
    ads2help, Jul 21, 2009 IP
  4. Webmaster Perks

    Webmaster Perks Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    First of all, I'd use mt_rand() instead of rand(). It's slightly faster and yields better "randomness". As for the if blocks, when it gets to be 3 or more, I general start looking at using switch/case. Particularly in your case, because I can see you needing to add additional cases over time. It's just easier to follow the flow (and update if necessary). That's just my opinion, though.

    As for the code, I'd do this:

    
    $intRandom = mt_rand(0, 10);
    
    switch (true) {
      case ($intRandom >= 0 && $intRandom < 5) :
        // some function
        break;
    
      case ($intRandom >= 5 && $intRandom < 7) :
        // some function
        break;
    
      case ($intRandom >= 7 && $intRandom < 11) :
        // some function 
        break;
    } 
    
    print($intRandom);
    
    Code (markup):
     
    Webmaster Perks, Jul 21, 2009 IP