odd or even

Discussion in 'PHP' started by gilgalbiblewheel, Sep 2, 2008.

  1. #1
    How do I distinguish the odd and even in an if statement:
    for($i=0; $i<count($spanId); $i++){
    	if((count($spanId[$i]) % 2) == 0){
    		$beginIllustratorNav = "<span id = \"".$spanId[$i]."\" style=\"float: right; margin: 5px; display: block; width: ".$spanWidth[$i]."px; height: ".$spanHeight[$i]."px; border: 1px solid #F6F5E3;\" >";
    		}else{
    		$beginIllustratorNav = "<span id = \"".$spanId[$i]."\" style=\"float: left; margin: 5px; display: block; width: ".$spanWidth[$i]."px; height: ".$spanHeight[$i]."px; border: 1px solid #F6F5E3;\" >";
    		}
    ...
    }
    PHP:

     
    gilgalbiblewheel, Sep 2, 2008 IP
  2. Shoro

    Shoro Peon

    Messages:
    143
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    if ($num % 2 == 0) {
        //Number is even
    }
    else {
        //Number is odd
    }
    PHP:
     
    Shoro, Sep 2, 2008 IP
  3. gilgalbiblewheel

    gilgalbiblewheel Well-Known Member

    Messages:
    435
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #3
    if(($i) % 2) == 0){

    But for some reason it gives me error:
     
    gilgalbiblewheel, Sep 2, 2008 IP
  4. Shoro

    Shoro Peon

    Messages:
    143
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Your brackets don't match up. Add another bracket at the start ("if ((($i) % 2) == 0)").
     
    Shoro, Sep 2, 2008 IP
  5. gilgalbiblewheel

    gilgalbiblewheel Well-Known Member

    Messages:
    435
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #5
    Bingo! thanks!
     
    gilgalbiblewheel, Sep 2, 2008 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    You can also do it this way:
    
    if ($i & 1)
    {
        // is odd
    }
    else
    {
        // Is even
    }
    
    PHP:
     
    nico_swd, Sep 3, 2008 IP