What does the percent sign mean in PHP?

后端 未结 6 1143
生来不讨喜
生来不讨喜 2020-12-03 04:25

What exactly does this mean?

$number = ( 3 - 2 + 7 ) % 7;
6条回答
  •  醉话见心
    2020-12-03 04:52

    It is the modulus operator:

    $a % $b = Remainder of $a divided by $b.

    It is often used to get "one element every N elements". For instance, to only get one element each three elements:

    for ($i=0 ; $i<10 ; $i++) {
        if ($i % 3 === 0) {
            echo $i . '
    '; } }

    Which gets this output:

    0
    3
    6
    9
    

    (Yeah, OK, $i+=3 would have done the trick; but this was just a demo.)

提交回复
热议问题