Do on Percent

Discussion in 'PHP' started by Silver89, Oct 18, 2008.

  1. #1
    I want to do a certain feature on about 3% of the sites visitors, is the best way to do this as follows?

    
    
    $number = rand(1,100);
    
    if($number == 1 || 2 || 3)
    {
    //Do this for 3%
    }
    
    
    
    PHP:
    If not how can I do this? If there's an easier way in php or javascript then I'd like to know,

    Thanks
     
    Silver89, Oct 18, 2008 IP
  2. jmatthew3

    jmatthew3 Peon

    Messages:
    29
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    you could do

    if ($number <= 3) {
    // DO X
    }
     
    jmatthew3, Oct 18, 2008 IP
    Silver89 likes this.
  3. Kyosys

    Kyosys Peon

    Messages:
    226
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Actually


    if ($number <= 3 && $number >= 1) {
    // DO X
    }
    This would check that the number is 3 or smaller, but 1 or bigger
    Anyway, the problem you're having is here:


    if($number == 1 || 2 || 3)
    you can't do it like that, it will check if 2 or 3 are true, which they are and always "do x"
    what you would need to do for correct coding using your method would be:

    if($number == 1 || $number == 2 || $number == 3)
     
    Kyosys, Oct 19, 2008 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    I'd probably do this so you only have to check one equals condition.

    if (rand(0,33)==0) {

    I know it's not exactly 3%, but you did say 'about 3%'. Should be close enough since it didn't sound like you needed accuracy.

    One thing for certain, I wouldn't be wasting a variable declaration on it. If you needed accurate, I'd just use:

    if (rand(0,99)<3) {

    Since he's doing rand(1,100), his value would NEVER be less than 1, so there's no reason to check for that!
     
    deathshadow, Oct 19, 2008 IP
  5. Kyosys

    Kyosys Peon

    Messages:
    226
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I must admit I completely skipped the line where he defined $number
     
    Kyosys, Oct 19, 2008 IP