PHP: Arrays — The Basics
A PHP array is not an ordinary array — it's a super data structure that acts as a list, a dictionary, and a set all in one. In PHP, arrays are the single data type you'll use most often, bar none.
1. What a PHP Array Really Is
A PHP array is essentially an ordered map. In plain English: it maps keys to values and remembers the insertion order.
PHP
<?php
// Indexed array: keys are automatically assigned numbers (0, 1, 2, ...)
$fruits = ["apple", "banana", "orange"];
// Associative array: keys are strings you specify
$user = [
"name" => "John",
"age" => 25,
"city" => "New York"
];
?>
| Language | List | Dictionary | PHP Array |
|---|---|---|---|
| Python | list |
dict |
array does both |
| JavaScript | Array |
Object / Map |
array does both |
| PHP | array |
array |
One structure handles everything |
2. Creating Arrays
PHP offers two syntaxes for creating arrays. [] is the modern syntax (PHP 5.4+) — use this one:
PHP
<?php
// Recommended syntax (PHP 5.4+)
$arr1 = []; // Empty array
$arr2 = [1, 2, 3]; // Indexed array
$arr3 = ["a" => 1, "b" => 2]; // Associative array
// Legacy syntax (for compatibility with older code)
$arr4 = array();
$arr5 = array(1, 2, 3);
$arr6 = array("a" => 1, "b" => 2);
?>
💡 Tip:
[] is 5 characters shorter than array(). There's no reason not to use it.
3. Accessing Array Elements
Use square brackets [] with a key to read or modify elements:
PHP
<?php
$fruits = ["apple", "banana", "orange"];
echo $fruits[0]; // apple (index starts at 0)
echo $fruits[1]; // banana
echo $fruits[2]; // orange
$fruits[1] = "strawberry"; // Modify the second element
echo $fruits[1]; // strawberry
// Access associative arrays by key name
$user = ["name" => "John", "age" => 25];
echo $user["name"]; // John
$user["age"] = 26; // Update the age
?>
⚠️ Warning: Accessing a key that doesn't exist triggers
Warning: Undefined array key. Get in the habit of checking with isset() or array_key_exists() first.
4. Adding and Removing Elements
PHP
<?php
// === Adding Elements ===
$arr = [1, 2];
$arr[] = 3; // Append to the end (the simplest syntax)
// $arr is now [1, 2, 3]
// Or use array_push (convenient when adding multiple)
array_push($arr, 4, 5);
// $arr is now [1, 2, 3, 4, 5]
// Add with a specific key
$arr["key"] = "value";
// === Removing Elements ===
unset($arr[2]); // Remove the element with index 2
// $arr is now [1, 2, 4, 5, "key"=>"value"]
// array_pop: remove and return the last element
$last = array_pop($arr);
// array_shift: remove and return the first element
$first = array_shift($arr);
?>
💡 Tip:
$arr[] = $val is PHP's most common append syntax — it's more concise than array_push() and marginally faster (no function call overhead).
5. Traversing Arrays
PHP
<?php
$fruits = ["apple", "banana", "orange"];
// foreach for indexed arrays (value only)
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
// foreach for associative arrays (key and value)
$user = ["name" => "John", "age" => 25, "city" => "New York"];
foreach ($user as $key => $value) {
echo "{$key}: {$value}<br>";
}
// name: John
// age: 25
// city: New York
?>
foreach doesn't care whether the array is indexed or associative — it traverses everything gracefully. That's the beauty of PHP's unified array type.
▶ サンプル: Traversing Nested Arrays
PHP
<?php
// Real-world: iterating through a student grade sheet
// (mixing associative and indexed arrays)
$classroom = [
["name" => "Alice", "scores" => ["Math" => 85, "English" => 92]],
["name" => "Bob", "scores" => ["Math" => 78, "English" => 88]],
];
foreach ($classroom as $student) {
$total = array_sum($student["scores"]);
echo "{$student['name']} — Total: {$total}<br>";
}
?>
6. Debugging Arrays
PHP
<?php
$user = [
"name" => "John",
"age" => 25,
"skills" => ["PHP", "MySQL", "JavaScript"]
];
// var_dump: the most detailed debug output (includes type and length)
var_dump($user);
/*
array(3) {
["name"]=> string(4) "John"
["age"]=> int(25)
["skills"]=> array(3) { [0]=> ... }
}
*/
// print_r: a concise version (shows structure only, no types)
print_r($user);
/*
Array ( [name] => John [age] => 25 [skills] => Array (...) )
*/
// In HTML, use <pre> tags for cleaner output
echo "<pre>";
print_r($user);
echo "</pre>";
?>
💡 Tip: Need to see the full array structure during development? →
var_dump(). Just need a quick look at the content? → echo "<pre>" + print_r(). In production? → Never output arrays directly; use logging.
7. count() — Counting Elements
PHP
<?php
$fruits = ["apple", "banana", "orange"];
echo count($fruits); // 3
$empty = [];
echo count($empty); // 0
// sizeof is an alias for count — they're identical
echo sizeof($fruits); // 3
?>
8. Checking If a Key or Value Exists
PHP
<?php
$user = ["name" => "John", "age" => 25];
// Check if a key exists
var_dump(array_key_exists("name", $user)); // bool(true)
var_dump(array_key_exists("email", $user)); // bool(false)
// Check if a value exists
var_dump(in_array("John", $user)); // bool(true)
var_dump(in_array("Jane", $user)); // bool(false)
?>
▶ サンプル: Safe Array Access Patterns
PHP
<?php
// When you're not sure a key exists, check first
$user = ["name" => "John"];
// Safe pattern
if (isset($user["age"])) {
echo $user["age"];
} else {
echo "Age not set";
}
// Concise pattern: use ?? to provide a default
$age = $user["age"] ?? "Unknown";
echo $age; // Unknown (because the "age" key doesn't exist)
?>
💡 Tip:
isset() vs. ??: isset($arr['key']) checks that the key exists and the value is not null. array_key_exists('key', $arr) checks only whether the key exists (returns true even if the value is null).
❓ よくある質問
Q How is a PHP array different from a JavaScript array?
A A PHP array is an all-in-one structure (list + dictionary rolled into one). JavaScript's Array is just a list; Object/Map handles the dictionary role. In PHP,
[0=>"a", 1=>"b"] and ["x"=>1, "y"=>2] are the exact same type.Q What's the difference between indexed and associative arrays?
A To PHP, there's essentially no difference — both are ordered maps. Indexed arrays have auto-assigned integer keys starting from 0. Associative arrays have custom string keys. You can even mix them:
["a"=>1, 2=>3, 4=>5] is completely valid.Q Why doesn't my foreach modify the original array?
A Unless you use
&$val for reference traversal, foreach ($arr as $val) gives $val as a copy of each array element. Modifying $val doesn't affect the original array.📖 まとめ
- PHP arrays are ordered maps — indexed and associative arrays are the same type under the hood
- Use
[]to create arrays;$arr[key]to access / modify elements $arr[] = $valappends an element;unset($arr[key])removes oneforeach ($arr as $key => $val)traverses arraysvar_dump()/print_r()debug array structuresisset()/??/array_key_exists()enable safe accesscount()counts elements;in_array()checks values;array_key_exists()checks keys
📝 練習問題
- Create an indexed array with 5 city names, output a numbered list with foreach, then use
$arr[]to append one more city and re-output the list. - Create an associative user array with at least 3 properties (name, age, email, skills list), then use foreach to display it as an HTML table. Handle the skills list (itself an array) specially — output it as a comma-separated string.
- Write a function
safeGet($arr, $key, $default)that safely retrieves a value from an array by key, returning the default value if the key doesn't exist.