Toán tử if của PHP
Toán tử so sánh
Câu lệnh If
thường chứa các điều kiện so sánh hai giá trị.
Ví dụ
Kiểm tra xem $t
có bằng 14 không:
$t = 14;
if ($t == 14) {
echo "Have a good day!";
}
Hãy tự mình thử »Để so sánh hai giá trị, chúng ta cần sử dụng toán tử so sánh.
Dưới đây là các toán tử so sánh PHP để sử dụng trong câu lệnh if
:
Operator | Name | Result | Try it |
---|---|---|---|
== | Equal | Returns true if the values are equal | Try it » |
=== | Identical | Returns true if the values and data types are identical | Try it » |
!= | Not equal | Returns true if the values are not equal | Try it » |
<> | Not equal | Returns true if the values are not equal | Try it » |
!== | Not identical | Returns true if the values or data types are not identical | Try it » |
> | Greater than | Returns true if the first value is greater than the second value | Try it » |
< | Less than | Returns true if the first value is less than the second value | Try it » |
>= | Greater than or equal to | Returns true if the first value is greater than, or equal to, the second value | Try it » |
<= | Less than or equal to | Returns true if the first value is less than, or equal to, the second value | Try it » |
Toán tử logic
Để kiểm tra nhiều điều kiện, chúng ta có thể sử dụng các toán tử logic, như toán tử &&
:
Ví dụ
Kiểm tra xem $a
có lớn hơn $b
không, VÀ nếu $a
nhỏ hơn $c
:
$a = 200;
$b = 33;
$c = 500;
if ($a > $b && $a < $c ) {
echo "Both conditions are true";
}
Hãy tự mình thử » Dưới đây là các toán tử logic PHP để sử dụng trong câu lệnh if
:
Operator | Name | Description | Try it |
---|---|---|---|
and | And | True if both conditions are true | Try it » |
&& | And | True if both conditions are true | Try it » |
or | Or | True if either condition is true | Try it » |
|| | Or | True if either condition is true | Try it » |
xor | Xor | True if either condition is true, but not both | Try it » |
! | Not | True if condition is not true | Try it » |
Chúng ta có thể so sánh bao nhiêu điều kiện tùy thích trong một câu lệnh if
:
Ví dụ
Kiểm tra xem $a
có phải là 2, 3, 4, 5, 6 hay 7 không:
$a = 5;
if ($a == 2 || $a == 3 || $a == 4 || $a == 5 || $a == 6 || $a == 7) {
echo "$a is a number between 2 and 7";
}
Hãy tự mình thử »