PHP: 演算子
Operators are the building blocks of a programming language — you combine variables and values with them to perform calculations and make decisions. PHP's operators are rich, intuitive, and many borrow directly from mathematical symbols.
1. Arithmetic Operators
▶ サンプル: All Arithmetic Operators
PHP
<?php
$a = 10;
$b = 3;
echo $a + $b; // 13 Addition
echo $a - $b; // 7 Subtraction
echo $a * $b; // 30 Multiplication
echo $a / $b; // 3.333... Division (note: PHP division always returns a float)
echo $a % $b; // 1 Modulus (remainder)
echo $a ** $b; // 1000 Exponentiation (PHP 5.6+, 10 to the power of 3)
// Negation
echo -$a; // -10 Negation
?>
2. Assignment Operators
Basic = assignment is straightforward. The real time-savers are the combined assignment operators:
PHP
<?php
$x = 10;
$x += 5; // $x = $x + 5; → 15
$x -= 3; // $x = $x - 3; → 12
$x *= 2; // $x = $x * 2; → 24
$x /= 4; // $x = $x / 4; → 6
$x %= 4; // $x = $x % 4; → 2
$x .= " yuan"; // $x = $x . " yuan"; → "2 yuan" (string append assignment)
?>
3. Comparison Operators
Used to compare two values; the result is true or false:
PHP
<?php
$a = 5;
$b = "5";
// Loose comparison (== compares value only, auto-converts types)
var_dump($a == $b); // bool(true) — 5 equals "5"
var_dump($a != $b); // bool(false)
// Strict comparison (=== compares both value and type)
var_dump($a === $b); // bool(false) — 5 doesn't equal "5" (different types)
var_dump($a !== $b); // bool(true)
// Greater / less than
var_dump($a > 3); // bool(true)
var_dump($a >= 5); // bool(true)
var_dump($a < 10); // bool(true)
var_dump($a <= 5); // bool(true)
// Spaceship operator (PHP 7+) <=>
// Returns -1 if left is smaller, 0 if equal, 1 if left is larger
echo 1 <=> 2; // -1
echo 2 <=> 2; // 0
echo 3 <=> 2; // 1
// Commonly used in sorting callbacks
?>
(1) == vs. === Decision Guide
| Scenario | Use | Reason |
|---|---|---|
| Form input validation | === |
User input "0" can be misjudged by == |
| Comparing database return values | === |
Databases may return numbers as strings |
| Comparing with constants | === |
Precise comparison |
Checking strpos() return value |
!== false |
0 would be misjudged by == false |
| Simple numeric comparison (both sides definitely numbers) | == |
It works, but === doesn't hurt either |
💡 Tip: Unless you have a clear reason to use
== (loose comparison), default to === (strict comparison). This prevents countless bugs caused by implicit type conversion.
▶ サンプル: Strict Comparison in Practice
PHP
<?php
// In a search engine, a user might enter "0"
$search = "0";
// ❌ Wrong approach
if ($search == false) {
echo "You didn't enter a search term"; // This runs! Because "0" == false
}
// ✅ Correct approach
if ($search === "") {
echo "You didn't enter a search term"; // "0" !== "", won't misjudge
}
?>
4. Logical Operators
Used to combine multiple conditions:
PHP
<?php
$age = 20;
$hasTicket = true;
// AND (both must be true)
var_dump($age >= 18 && $hasTicket); // bool(true)
var_dump($age >= 18 and $hasTicket); // bool(true) — lower precedence than &&
// OR (at least one must be true)
var_dump($age < 18 || $hasTicket); // bool(true) — has a ticket, so can enter
var_dump($age < 18 or $hasTicket); // bool(true) — lower precedence than ||
// NOT (negation)
var_dump(!$hasTicket); // bool(false)
var_dump(!false); // bool(true)
// XOR (true when the two are different)
var_dump(true xor false); // bool(true)
var_dump(true xor true); // bool(false)
?>
⚠️ Warning:
&& and and behave differently! $a = true && false; results in false (&& has higher precedence than =), while $a = true and false; results in true (= has higher precedence than and). Always use && and ||, not and and or.
5. String Operators
PHP has only two string operators:
| Operator | Action | Example | Result |
|---|---|---|---|
. |
Concatenate | "Hello" . " PHP" |
"Hello PHP" |
.= |
Append | $s = "A"; $s .= "B"; |
$s = "AB" |
PHP
<?php
$name = "John";
echo "Hello, " . $name . "!"; // Hello, John!
$html = "<div>";
$html .= "<h1>Title</h1>";
$html .= "<p>Content</p>";
$html .= "</div>";
echo $html;
// <div><h1>Title</h1><p>Content</p></div>
?>
6. Ternary Operator (?:)
The ternary operator is a shorthand for if...else:
▶ サンプル: Ternary vs. Null Coalescing Compared
PHP
<?php
$age = 20;
// Format: condition ? value_if_true : value_if_false
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status; // Adult
// The above is equivalent to:
if ($age >= 18) {
$status = "Adult";
} else {
$status = "Minor";
}
// PHP 5.3+ shorthand (omit the middle part)
$username = $_GET['name'] ?: "Guest";
// Equivalent to: use $_GET['name'] if it's truthy, otherwise "Guest"
?>
💡 Tip: The ternary operator is great for one-line decisions. But never nest ternaries —
$a ? $b ? $c : $d : $e is completely unreadable.
7. Null Coalescing Operator (??)
This is one of the most practical features introduced in PHP 7:
PHP
<?php
// ?? operator: use the left side if it's not null, otherwise use the right side
$username = $_GET['user'] ?? "Anonymous";
// Equivalent to: isset($_GET['user']) ? $_GET['user'] : "Anonymous"
// ??= operator (PHP 7.4+): assign only if the left side is null
$config = null;
$config ??= "default"; // $config is now "default"
$config2 = "existing value";
$config2 ??= "default"; // $config2 is still "existing value" (not null, so no overwrite)
// The difference between ?? and ?:
$name = "";
echo $name ?: "default"; // "default" (empty string is falsy)
echo $name ?? "default"; // "" (empty string is not null)
?>
| Operator | Logic | How "" is handled |
|---|---|---|
?: |
Use the right side if the left is falsy | "" → use right side |
?? |
Use the right side if the left is null or undefined | "" → use left side ("" is not null) |
💡 Tip: When handling user input,
?? is usually safer than ?: because a user might intentionally enter an empty string "", which is a valid input.
8. Operator Precedence
When an expression has multiple operators, PHP uses precedence to decide which to evaluate first:
| Precedence | Operators |
|---|---|
| High | ** (exponentiation) |
!, ~, ++, -- |
|
*, /, % |
|
+, -, . |
|
<, <=, >, >= |
|
==, !=, ===, !== |
|
&& |
|
| ` | |
?? |
|
?: (ternary) |
|
| Low | =, +=, .= , etc. |
PHP
<?php
// Don't memorize the table — use parentheses to clarify intent
$result = $a + $b * $c; // Unclear
$result = $a + ($b * $c); // Clear
// Same for complex conditions
if (($age >= 18 && $hasTicket) || $isVip) {
echo "Entry allowed";
}
?>
💡 Tip: You don't need to memorize the operator precedence table. When in doubt, add parentheses. Code is written for humans; parentheses make your intent immediately obvious.
❓ よくある質問
Q When exactly should I use
== vs. ===?A Default to
===. Use == only when you genuinely need automatic type coercion (e.g., comparing numbers from different sources). For strpos() checks, comparisons with false/null, you must use ===.Q How do I choose between
?? and ?:?A Use
?? when pulling values from GET/POST (the user might not send the parameter at all). Use ?: when you care whether a variable has "actual content" (empty string counts as no content). Use ?? for array key existence checks too.Q Why does
1 + "10 cats" produce 11 and not 1?A When PHP converts a string to a number, it reads from the beginning until it hits the first non-numeric character.
"10 cats" starts with "10", so it converts to 10. If the string starts with a non-numeric character (e.g., "cats 10"), it converts to 0.📖 まとめ
- Use
.to concatenate strings and.=to append (not+) ===performs strict comparison (value and type) — prefer it by default<=>spaceship operator returns -1/0/1 — perfect for sorting&&has higher precedence thanand— only use&&and||??checks for null/undefined;?:checks for falsy — prefer??for user input- When unsure about precedence, add parentheses; clarity beats brevity
📝 練習問題
- Create two variables representing a user's age and membership status, then use logical operators to determine whether they can enter (age ≥ 18 OR is a member).
- Use the
??operator to safely retrieve the URL parameterpagewith a default of 1; then use the ternary operator to display "Homepage" if page ≤ 1, or "Page N" otherwise. - Write a combined operator exercise: given a product price and discount rate, calculate the discounted price and format the output to two decimal places.