In PHP, you can use the remainder operator "%" and the equality operator "==" to determine whether a number is odd or even. Just use the "%" operator to get the specified number divided by 2 The remainder after that, and use the "==" operator to determine whether the remainder is 0; the syntax is "$num%2==0", if true is returned, it is an even number, otherwise it is an odd number.
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
The essence of judging whether a number is odd or even is actually It is to judge whether the number is divisible by 2:
If it is divisible by 2, then it is an even number
If it is not divisible by 2, then It’s an odd number
So how to implement the integer division function in PHP?
In PHP, you can use the remainder operator "%" to determine whether it is divisible.
If a number is divided by 2 and there is no remainder (0), then it is divisible by 2, which is an even number
If If a number is divided by 2 and there is a remainder (not 0), then it is not divisible by 2, that is, it is an odd number.
Okay, after analyzing this, everyone should understand how to judge whether Is it an odd number or an even number? is to use the "%" operator. Grammar:
$num%2==0
Let’s learn more about it through an example:
<?php header('content-type:text/html;charset=utf-8'); function f($num){ if($num%2==0){ echo $num." 能被2整除, 是偶数!<br>"; }else{ echo $num." 不能被2整除, 是奇数!<br>"; } } f(1); f(2); f(3); f(4); f(5); ?>
PHP Video Tutorial"
The above is the detailed content of How to determine whether a number is odd or even in php. For more information, please follow other related articles on the PHP Chinese website!