PHP
📦 PHP Arrays: Fundamentals & Syntax
An Array in PHP is a compound data type that enables developers to store, manage, and manipulate multiple values under a single variable name in an ordered, structured format.
-
Real-World Analogy: Think of an array as a shopping list containing
["Bread", "Milk", "Cheese"]—instead of declaring three separate variables, all items are grouped together inside one container.
🔍 What Does print_r() Do?
The print_r() function displays information about an array in a human-readable format. It is an essential diagnostic tool used during development and debugging to inspect array elements and key-value mapping.
🛠️ How Arrays Are Created
PHP provides two syntaxes for declaring arrays: the legacy array() language construct and the modern short square bracket syntax ([]).
// Method 1: Using array() function
$shoppingList1 = array("Bread", "Milk", "Cheese");
// Method 2: Using square brackets [] (Recommended)
$shoppingList2 = ["Bread", "Milk", "Cheese"];
// Output array contents
print_r($shoppingList2);
/*
Output:
Array
(
[0] => Bread
[1] => Milk
[2] => Cheese
)
*/
📋 Core Rules for PHP Arrays
Adhering to array key naming conventions prevents syntax conflicts and unexpected runtime behaviors:
-
Allowed Characters: Custom string keys can contain letters (
A-Z,a-z), numbers (0-9), and underscores (_). - Forbidden Characters: Do not use spaces, non-ASCII/special characters, or mathematical symbols inside key names.
-
Case Sensitivity: Array key names are case-sensitive. For example,
$arr["name"]and$arr["Name"]reference two distinct keys. - Unique Keys: Each key must be unique within the same array level. Re-using an existing key overwrites its previous value.
-
Automatic Numeric Indexing: If no explicit keys are defined, PHP automatically assigns zero-based integer keys starting from
0and incrementing by1.
📊 Keyed vs. Non-Keyed (Indexed) Arrays
| Type | Key Structure | Example Syntax | Best Used For |
|---|---|---|---|
| Indexed Array | Automatic numeric index (0, 1, 2...) |
["PHP", "HTML", "CSS"] |
Sequential lists and ordered collections. |
| Associative Array | Named string keys | ["id" => 101, "role" => "Admin"] |
Structured data records and key-value mapping. |
-
📝 Short Summary
- Arrays allow grouping multiple related items under a single variable name.
-
Use
print_r()orvar_dump()to inspect array structures during backend development. -
Square brackets
[]represent the clean, modern PHP syntax for declaring array elements.
