-3

I have a table with set of information. I set the id for each row (in about 30 rows of info). Is there any way that I can tell PHP to get only the odd or even id number to display on the web page?

I want to display them in two columns: rows with an odd id on the left, and those with an even id on the right.

How would that code be written? Or.. can anyone tell me some sources or tutorials to read?

1
  • 1
    If the number is evenly divisible by 2 it's even, else it's odd. Check if the ID is evenly divisible by 2. Basic algebra. Commented Aug 10, 2011 at 20:38

4 Answers 4

7
$id % 2 == 0 //is even

$id % 2 == 1 //is odd
0
1

Use MODULO to check whether value is odd/even check here for more information

so :

if ($counter % 2) {
    // ODD RESULTS
} else {
    // EVEN RESULTS
}
1
  • It's the modulo operator, not MODULE, and its truth table is opposite of what you've written. The remainder is 0, false, when even and 1, true, when odd. Commented Aug 10, 2011 at 20:39
0

This is a fairly standard pattern.

Since you're iterating through your results in sequential order, and since tables are built in horizontal order, your pseudo-code looks like this:

<table>
   <tr>
   FOREACH RESULT i
      <td>DATA(i)</td>
      IF i IS ODD
         </tr><tr>
      ENDIF
   ENDFOREACH
   </tr>
</table>

Ideally you would add more conditionals to avoid empty rows, but this ought to get you started.

1
  • @DonSeba: No. It is pseudo-code, as I said. I'll leave the implementation to the OP's imagination. Commented Aug 10, 2011 at 21:05
-1

Might be simpler to pull everything in your query, add a css class to each row (either odd or even) and then use a very simple jquery command to display the ones you want

 $(document).ready(function () {
  $('.odd').display( etc....

Something like that...

3
  • But this isn't what the OP asked for! He doesn't want alternate-row styling; he wants two columns. Commented Aug 10, 2011 at 20:42
  • why the downvote? jquery isn't just for alternate row styling. Commented Aug 10, 2011 at 20:51
  • No, but that's what your answer talks about. It addresses neither the rendering of columns, nor creating the distinction between odd and even. It only seems to talk about "doing something" with a row marked with a .odd, when in fact the rows being odd or even is not what is being asked about! Commented Aug 10, 2011 at 20:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.