In computer programming, a standard scalar variable can store only one piece of information at any given moment (e.g. $score = 95;). If you need to manage a list of 100 student names, declaring 100 individual variables ($student1, $student2...) would be virtually impossible to maintain. An array is a specialized, composite data structure capable of holding multiple values under a single identifier name.
Figure 4: Visual memory architecture comparing Indexed, Associative, and Multidimensional Arrays in PHP.
In PHP, all arrays fall into one of three classifications based on their key structure:
| Array Classification | Key Type & Characteristics | Quick Code Example |
|---|---|---|
| Indexed Array | Uses auto-incrementing numeric keys (0, 1, 2, 3...). Ideal for ordered sequential lists. | $fruits = ["Apple", "Mango", "Banana"]; |
| Associative Array | Uses named string keys (Key → Value). Ideal for dictionary and record structures. | $user = ["name" => "Alex", "age" => 21]; |
| Multidimensional Array | Contains nested arrays within an outer array. Ideal for 2D grids, tables, and matrices. | $matrix = [[1, 2], [3, 4], [5, 6]]; |
[] vs array()Originally in PHP 5, arrays were instantiated using the array() construct. Modern PHP 7 and 8 provide the clean, square-bracket short array syntax [], which is the universal standard in contemporary frameworks:
<?php
// Modern Short Syntax (Recommended)
$languages = ["PHP", "JavaScript", "Python", "SQL"];
// Legacy Syntax (Still supported for backward compatibility)
$frameworks = array("Laravel", "Symfony", "CodeIgniter");
?>
count() and sizeof()To count how many elements reside inside an array, use the built-in count() function (or its alias sizeof()):
<?php
$students = ["Priya", "Sunil", "Aakash", "Meena"];
echo "Total Enrolled Students: " . count($students); // Outputs: 4
?>
PHP supports clean array destructuring, allowing you to unpack array elements directly into variables:
<?php
$studentRecord = [101, "Rahul Sharma", 94.5];
// Destructure array into standalone variables
[$id, $name, $percentage] = $studentRecord;
echo "ID: $id | Name: $name | Score: $percentage%";
?>
High-Frequency Exam Question:
Q: What data types can be stored inside a PHP array?
A: In PHP, arrays are heterogeneous (dynamically typed). A single array can store a mixture of strings, integers, floats, booleans, objects, resources, and even other nested arrays all within the same container!
Exercise 21.1: Create an array storing the names of 6 subjects in your current semester. Display the count and print the first and last subject.
Exercise 21.2: Write a script that checks whether an array contains a specific value using in_array().