Help us understand the problem. What is going on with this article?

PHP - 偶数or奇数を判定する方法

対象の数字が偶数なのか、奇数なのか、if文で判定します。

・パターン1
対象の数字($A)を2で割った時、余りがないかを確認しています。
余りがない場合は「偶数」です。

<?php
if($A % 2 == 0){
<偶数の場合>
}else{
<奇数の場合>
}
?>

ビット演算子を使用します。
ビットは2進数なので、2で繰り上がっていきます。
なので、2で割り切れない数字(奇数)は2進数化した10進数の末尾が1となります。

<?php
if($A & 1){
<奇数の場合>
}else{
<偶数の場合>
}
?>

◼︎用語の詳細
・A % B
代数演算子。剰余。AをBで割った時の余り。

・A & B
ビット演算子。ビット積。

nnnnn000
PHPの勉強メモです。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした