开发者

PHP % operator, what result should be returned?

$djs_a开发者_JAVA百科ll_num = mysql_num_rows($djs_all_db); while($djs_all = mysql_fetch_array( $djs_all_db )) { if ($djs_all_num % "2") {

With my if () statement, this should halve the amount of rows, and so in the else further on it should display the rest.

Is this correct?


It doesn't halve anything. It gives the remainder with 2 as divisor. This will be 0 if even, 1 if odd. So if djs_all_num is odd, it will enter the if statement. You should write 2 instead. Using the implicit conversion from string to int is confusing and unnecessary.

Note that this does not operate per-row, since the left operand is the total row count, not the row index. To use a row index, do something like:

$row_ind = 0;
$djs_all_num = mysql_num_rows($djs_all_db);
        while($djs_all = mysql_fetch_array( $djs_all_db )) {
        if ($row_ind++ % 2) {


The % operator aka Modulus (edit)determines if there was a remainder(/edit). Used quite oftenly to determine odd / even rows.

So a 1 % 2 would equal .5 1 (I think if my math is correct). 2 % 2 = 0.

Hope that helps.

EDIT: Sorry did some local testing and found out my statement was incorrect, modified to be correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜