Wednesday, 7 April 2021

Php: what is the sign of modulo operator result?

The result of the modulo operator % has the same sign as the dividend.

 

Example

$a % $b will have the same sign as $a.

 

modulo_operator_sign.php

#!/usr/bin/php

<?php
$a = 11;
$b = - 11;

$result1 = $a % 3; // 2
$result2 = $a % - 3; // 2
$result3 = $b % 3; // -2
$result4 = $b % - 3; // -2

echo "$a % 3 : $result1\n";
echo "$a % -3 : $result2\n";
echo "$b % 3 : $result3\n";
echo "$b % -3 : $result4\n";

?>

 

Output

$./modulo_operator_sign.php 

11 % 3 : 2
11 % -3 : 2
-11 % 3 : -2
-11 % -3 : -2

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment