Home >Backend Development >PHP Problem >How to determine whether a number is odd or even in php

How to determine whether a number is odd or even in php

青灯夜游
青灯夜游Original
2022-05-20 11:50:117471browse

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.

How to determine whether a number is odd or even in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
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);
?>

How to determine whether a number is odd or even in php

## Recommended learning: "

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn