PHP: 変数とデータ型
Variables are like labeled boxes — you put data inside a box, attach a label, and later use the label to find it. In PHP, every variable label must start with
$— that's PHP's most distinctive feature.
1. Declaring and Naming Variables
Declaring a variable in PHP is simple: $ + variable name = value. You don't need to declare a type first, unlike C or Java.
PHP
<?php
$name = "John"; // String
$age = 25; // Integer
$height = 1.75; // Float
$isStudent = true; // Boolean
?>
(1) Naming Rules
| Rule | ✅ Correct | ❌ Wrong |
|---|---|---|
Must start with $ |
$name |
name (no $) |
Letter or underscore after $ |
$name, $_name |
$1name, $-name |
| Followed by letters, digits, underscores | $user_id, $user2 |
$user-id, $user@id |
| Case-sensitive | $name ≠ $Name |
|
| Use camelCase | $firstName, $userAge |
💡 Tip: PHP variable names starting with
$ are inherited from Perl. This makes PHP variables instantly recognizable when mixed with HTML.
2. PHP's Eight Data Types
PHP has 8 primitive types, grouped into three categories:
| Category | Type | Example | Description |
|---|---|---|---|
| Scalar | string |
"Hello" |
A sequence of characters |
int |
42 |
Whole numbers | |
float |
3.14 |
Floating-point numbers (also called double) |
|
bool |
true / false |
Boolean values | |
| Compound | array |
[1, 2, 3] |
Ordered map of values |
object |
new User() |
Instances of classes | |
callable |
A callback function | Callable type | |
iterable |
Traversable | Iterable type | |
| Special | null |
null |
Represents no value |
resource |
File handle / DB connection | Reference to an external resource |
▶ サンプル: Inspecting Variable Types with var_dump
PHP
<?php
$name = "John";
$age = 25;
$price = 19.99;
$isValid = true;
$nothing = null;
var_dump($name); // string(4) "John"
var_dump($age); // int(25)
var_dump($price); // float(19.99)
var_dump($isValid); // bool(true)
var_dump($nothing); // NULL
?>
3. Strings — Basic Usage
PHP
<?php
$s1 = 'PHP Tutorial'; // Single quotes: literal string, no variable parsing
$s2 = "PHP Tutorial"; // Double quotes: parses variables and escape sequences
$name = "John";
echo 'Hello $name'; // Hello $name — single quotes don't parse variables
echo "Hello $name"; // Hello John — double quotes parse variables
?>
| Syntax | Parses variables? | Parses escape sequences? | Best for |
|---|---|---|---|
'Single quotes' |
No | Only \\ and \' |
Plain text |
"Double quotes" |
Yes | Parses \n \t etc. |
Embedding variables |
We'll dive deeper into strings in the next lesson.
▶ サンプル: Single vs. Double Quotes Compared
PHP
<?php
$name = "John";
// Single quotes: output exactly as written
echo 'Hello, $name!\nNice weather today.';
// Output: Hello, $name!\nNice weather today.
// Double quotes: parse variables and escape sequences
echo "Hello, $name!\nNice weather today.";
// Output: Hello, John! (newline) Nice weather today.
?>
4. Integers (int) and Floats (float)
PHP
<?php
$decimal = 42; // Decimal
$hex = 0x2A; // Hexadecimal (=42)
$octal = 052; // Octal (=42)
$binary = 0b101010; // Binary (=42)
$float1 = 3.14; // Float
$float2 = 1.2e3; // Scientific notation = 1200
$float3 = 7E-10; // Scientific notation = 0.0000000007
?>
⚠️ Warning: Floating-point numbers can't precisely represent decimal fractions.
0.1 + 0.2 in PHP does not equal 0.3 — it's something like 0.30000000000000004. When working with money, store amounts in cents as integers or use the bcmath extension.
5. Booleans (bool)
Booleans have only two values: true and false. They're case-insensitive, but the convention is lowercase.
PHP
<?php
$isLogin = true;
$isAdmin = false;
if ($isLogin) {
echo "Welcome back!";
}
?>
💡 Tip:
echo true outputs 1; echo false outputs an empty string (nothing shows). Use var_dump() to inspect boolean values.
6. Type-Checking Functions
PHP
<?php
$name = "John";
$age = 25;
var_dump(is_string($name)); // bool(true)
var_dump(is_int($age)); // bool(true)
var_dump(is_float($age)); // bool(false)
var_dump(is_bool($age)); // bool(false)
var_dump(is_array($name)); // bool(false)
// gettype() returns the type name (for debugging, not logic)
echo gettype($name); // string
?>
| Function | Checks For |
|---|---|
is_string() |
String |
is_int() |
Integer |
is_float() |
Float |
is_bool() |
Boolean |
is_array() |
Array |
is_null() |
NULL |
is_numeric() |
Number or numeric string |
7. Type Conversion
PHP is a loosely typed language and automatically converts types. You can also convert explicitly:
PHP
<?php
// Automatic conversion
$result = "10" + 5; // 15 ("10" converted to number)
$text = "10" . 5; // "105" (5 converted to string)
// Explicit conversion
$intVal = (int) "123"; // 123
$floatVal = (float) "3.14"; // 3.14
$strVal = (string) 123; // "123"
$boolVal = (bool) 1; // true
?>
▶ サンプル: Type Conversion in Practice
PHP
<?php
// String to number
$a = (int) "42";
echo $a + 8; // 50
// Number to string
$b = (string) 100;
echo "Price: " . $b . " yuan"; // Price: 100 yuan
// Boolean conversion rules: these values are treated as false
echo (int)((bool)0); // 0
echo (int)((bool)""); // 0
echo (int)((bool)[]); // 0
echo (int)((bool)null); // 0
// All other values are true
?>
⚠️ Warning:
"0", "", 0, [], and null are all false in a boolean context. If you can't remember, just test it with var_dump((bool)$x).
8. isset() and empty()
These are three of the most frequently used variable-handling functions in PHP:
PHP
<?php
$var1 = "Hello";
$var2 = null;
// isset(): variable is set and not null → true
var_dump(isset($var1)); // bool(true)
var_dump(isset($var2)); // bool(false)
var_dump(isset($notExist)); // bool(false) — doesn't exist
// empty(): variable is empty → true ("", 0, "0", null, false, [] are all "empty")
var_dump(empty($var1)); // bool(false) — "Hello" is not empty
var_dump(empty($var2)); // bool(true) — null is empty
var_dump(empty(0)); // bool(true) — 0 is considered empty!
var_dump(empty($notExist)); // bool(true) — not existing is also considered empty
?>
▶ サンプル: isset vs. empty Side by Side
PHP
<?php
function testVar(string $label, mixed $value): void {
echo "$label — isset: " . (isset($value) ? 'true' : 'false');
echo " | empty: " . (empty($value) ? 'true' : 'false') . "<br>";
}
testVar('"Hello"', "Hello");
testVar('""', "");
testVar('0', 0);
testVar('null', null);
// Observe the isset and empty results for each value
?>
🔥 Common Mistake:
empty(0) returns true! The number 0 is considered "empty." When validating whether a number was entered, use isset() combined with is_numeric() — don't use empty().
❓ よくある質問
Q Why does echo false show nothing?
A Because
echo false is equivalent to echo "" (empty string). To inspect a boolean value, use var_dump($var) or echo $var ? 'true' : 'false'.Q When should I use
isset() vs. empty()?A
isset() checks "does the variable exist and is it not null?" — use it to check if a form was submitted. empty() checks "is the variable empty/zero/false?" — use it to validate whether input is blank. For checking numeric input, use isset() + is_numeric() — never empty().Q PHP is loosely typed. Does that make type bugs common?
A Develop two habits: (1) Use
=== instead of == for comparisons (strict comparison doesn't auto-convert types); (2) Add type declarations to function parameters (PHP 7+ supports this). We'll cover these in detail later.📖 まとめ
- Variables start with
$, use camelCase naming, and are case-sensitive - PHP has 8 types: 4 scalar + 4 compound/special
var_dump()shows a variable's value and type — your go-to debugging tool- Double quotes parse variables; single quotes don't
(int),(string), etc. perform explicit type castingisset()checks existence and non-null;empty()checks emptiness (0 is also considered empty)
📝 練習問題
- Create 3 variables of different types (string, integer, boolean) and use
var_dump()andgettype()to inspect each one. - Write code to test how
isset()andempty()behave on these values:"Hello","",0,null, and an undefined variable. Summarize the differences. - Write a type-conversion exercise: take a user-input price string like
"$99.9"and convert it into a computable float. Try(float)— does it work directly? If not, think about how to handle it.