Home > Article > Backend Development > How to determine whether a number is even in php
In PHP, you can use the remainder operator "%" and the equality operator "==" to determine whether a number is even. The syntax is "value % 2 ==0". An even number is a number that is divisible by 2. You only need to use "%" to get the remainder of the specified number divided by 2, and then use "==" to determine whether the remainder is 0; if the remainder is 0, the number is an even number.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php determines a number Is it an even number
In PHP, if you want to determine whether a number is an even number, you only need to determine whether the number is divisible by 2.
In other words, it is the number that has a remainder of 0 when divided by 2.
Use the remainder operator "%" and the equality operator "==" to determine whether a number is divisible by 2, that is, whether it is an even number.
Implementation code:
<?php header('content-type:text/html;charset=utf-8'); function f($num){ if($num % 2 == 0){ echo $num."是一个偶数<br>"; } else{ echo $num."不是一个偶数<br>"; } } f(2); f(3); f(4); f(5); f(6); ?>
Description:
Remainder operator "%", used to find Remainder operation, find the remainder of division operation.
"%" mainly operates on integers, but also applies to floating point numbers. If the dividend ($a) is negative, the result obtained is also a negative value.
Equality operator "==", if the values of $a and $b are equal after type conversion, it returns TRUE, otherwise it returns FALSE
Congruence operator "===", If $a and $b are not only equal in value, but also have equal types of values, then return TRUE, otherwise return FALSE
It is important to distinguish between "equal" and "congruent":
Equal == only compares the values of two variables
Congruent=== not only compares the values of the expressions on both sides of the operator, but also The data types will also be compared. Only when the values and data types on both sides are equal, the operation result will be TRUE.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to determine whether a number is even in php. For more information, please follow other related articles on the PHP Chinese website!