Arrays in PHP
An array is a special variable that can store multiple values in a single variable, instead of creating separate variables for each value.
Why Arrays are Needed?
Without arrays:
$student1 = "Amit";
$student2 = "Rohit";
$student3 = "Neha";
With arrays:
$students = array("Amit", "Rohit", "Neha");
Exam Definition: An array is a collection of similar or different data types stored under a single variable name.
---
Types of Arrays in PHP
PHP mainly supports three types of arrays:
- Indexed Array
- Associative Array
- Multidimensional Array
---
How to Create an Array
1. Indexed Array
Uses numeric index (0,1,2,...).
Syntax
$arrayName = array(value1, value2, value3);
Example
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Red
2. Associative Array
Uses named keys instead of numbers.
Syntax
$arrayName = array(key => value);
Example
$student = array(
"name" => "Rohit",
"age" => 21,
"course" => "BCA"
);
echo $student["name"];
Real-time Use: Storing database records.
3. Multidimensional Array
An array containing one or more arrays.
Example
$students = array(
array("Rohit", 21),
array("Amit", 22),
array("Neha", 20)
);
echo $students[1][0]; // Amit
Real-time Use: Storing table-like data.
Short Array Syntax
$numbers = [10, 20, 30];
Exam Tip: PHP supports both traditional and short array syntax.