0

I've a short MySQL-Query on my website:

...

for($i=0;$i<$sql->getRows();$i++) {
    $id = $sql->getValue("id");
    $name = $sql->getValue("name");
}

Is there a way to get every odd-row (every second row!) inside the query by an if-statement?

e.g.

for($i=0;$i<$sql->getRows();$i++) {
    $id = $sql->getValue("id");
    $name = $sql->getValue("name");

    if(ROW = ODD) {
        // DO SOMETING
    } else {
        // DO SOMETING ELSE
    }
}
Jonas
  • 475
  • 5
  • 17

1 Answers1

0

Assuming an odd number is a digit that cannot return a whole number when it is divided by 2 you can try something like this:

/**
 * 
 * @param int $rowNumber
 * @return bool event number
 */
function isEven($rowNumber){
    $r = $rowNumber/2;
    return ctype_digit((string) $r);  
}

for($i=0;$i<$sql->getRows();$i++){

    if(isEven($i)){
        //do even code access the rowdata with ro
    }
    else{
        //do odd code
    }    
}

ctype_digit() will return true if all characters in a string are numeric. If it is an odd number the result will contain a decimal point and therefore return false.

As per @DrKey comment, he is right, a cleaner isEven function would look like

/**
 * 
 * @param int $rowNumber
 * @return bool event number
 */
function isEven($rowNumber){
    return $rowNumber % 2 == 0;
}
Jason Joslin
  • 1,154
  • 8
  • 23
  • 2
    You are incrementing `$i` two times per row and `isEven` function can simply be `return $rowNumber % 2 == 0`. – DrKey Mar 22 '17 at 00:11
  • Ahh yeah my bad i orginally had it in a foreach loop so was manually doing the increment. when i changed it back to a for loop i forgot to remove that increment – Jason Joslin Mar 22 '17 at 00:14