Working With Arrays in PHP
Working With Arrays in PHP
An array in PHP is a special variable that allows you to store multiple values in a single variable.
Arrays are a fundamental data structure and are highly versatile, enabling you to organize and
manipulate data efficiently.
1. Indexed Arrays
Definition
• Indexed arrays use numeric keys (starting from 0 by default) to access elements.
• They store a collection of values that are typically related but do not need specific labels.
Syntax
Example
// Accessing elements
echo $fruits[0]; // Outputs: Apple
echo $fruits[1]; // Outputs: Banana
Real-World Application
2. Associative Arrays
Definition
// Newer syntax
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
Example
$person = [
"name" => "Alice",
"age" => 28,
"city" => "Paris"
];
// Accessing elements
echo $person["name"]; // Outputs: Alice
echo $person["city"]; // Outputs: Paris
Real-World Application
3. Multidimensional Arrays
Definition
Syntax
BASICS OF PHP - ARRAYS SOMATECH IT
// Creating a multidimensional array
$users = array(
array("John", 30, "New York"),
array("Alice", 25, "Paris"),
array("Bob", 35, "London")
);
Example
$users = [
["name" => "John", "age" => 30, "city" => "New York"],
["name" => "Alice", "age" => 25, "city" => "Paris"],
["name" => "Bob", "age" => 35, "city" => "London"]
];
// Accessing elements
echo $users[0]["name"]; // Outputs: John
echo $users[1]["city"]; // Outputs: Paris
Real-World Application
Problem
Indexed Array
Associative Array
$grades = [
"Math" => 85,
"English" => 90,
"Science" => 78
];
Multidimensional Array
$students = [
["name" => "John", "grades" => ["Math" => 85, "English" => 90,
"Science" => 78]],
["name" => "Alice", "grades" => ["Math" => 88, "English" => 92,
"Science" => 84]],
];
Understanding and mastering arrays is crucial for building dynamic and robust PHP applications.