When working with PHP, managing data efficiently is one of the most important tasks for developers. Arrays in PHP provide a structured way to store, organize, and manipulate multiple values under a single variable name. Instead of creating separate variables for each piece of data, arrays allow you to handle collections of related values easily.
In this tutorial, we’ll explore PHP arrays, their types, usage, and real-world applications with practical code examples.
1. What is an Array in PHP?
An array is a special variable that can hold more than one value at a time.
For example, instead of:
$car1 = "BMW";
$car2 = "Audi";
$car3 = "Mercedes";
We can use an array:
$cars = array("BMW", "Audi", "Mercedes");
Here, $cars
holds three values under one variable.
2. Types of Arrays in PHP
PHP provides three main types of arrays:
- Indexed Array – Uses numeric indexes.
- Associative Array – Uses named keys.
- Multidimensional Array – Arrays within arrays.
2.1 Indexed Arrays
An indexed array assigns numeric indexes (starting from 0) to values.
Example:
<?php
$fruits = array("Apple", "Banana", "Mango");
echo $fruits[0]; // Output: Apple
echo $fruits[2]; // Output: Mango
?>
You can also create an indexed array without array()
using square brackets:
$colors = ["Red", "Green", "Blue"];
2.2 Associative Arrays
An associative array uses custom keys (strings) instead of numbers.
Example:
<?php
$student = array("name" => "Ravi", "age" => 20, "city" => "Delhi");
echo $student["name"]; // Output: Ravi
?>
Associative arrays are very useful for representing key-value pairs like user profiles, product details, etc.
2.3 Multidimensional Arrays
A multidimensional array stores arrays inside other arrays.
Example:
<?php
$users = array(
array("name" => "Amit", "age" => 25),
array("name" => "Neha", "age" => 22),
array("name" => "Raj", "age" => 28)
);
echo $users[1]["name"]; // Output: Neha
?>
This is commonly used in databases, JSON responses, and tabular data.
3. Array Functions in PHP
PHP provides built-in functions to manipulate arrays.
3.1 Adding Elements
$numbers = array(1, 2, 3);
array_push($numbers, 4, 5);
print_r($numbers); // [1,2,3,4,5]
3.2 Removing Elements
array_pop($numbers); // Removes last element
array_shift($numbers); // Removes first element
3.3 Sorting Arrays
$fruits = ["Mango", "Apple", "Banana"];
sort($fruits); // Ascending order
rsort($fruits); // Descending order
3.4 Associative Array Sorting
$marks = ["Ravi" => 85, "Neha" => 92, "Amit" => 78];
asort($marks); // Sort by values
ksort($marks); // Sort by keys
3.5 Searching in Arrays
$colors = ["Red", "Green", "Blue"];
if (in_array("Green", $colors)) {
echo "Found Green!";
}
3.6 Array Length
echo count($colors); // 3
4. Iterating Over Arrays
We can loop through arrays using for, foreach, or while.
4.1 For Loop (Indexed Arrays)
$fruits = ["Apple", "Banana", "Mango"];
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}
4.2 Foreach Loop (Associative Arrays)
$student = ["name" => "Ravi", "age" => 20, "city" => "Delhi"];
foreach ($student as $key => $value) {
echo "$key : $value <br>";
}
5. Real-World Examples of PHP Arrays
5.1 Shopping Cart Example
$cart = [
["item" => "Laptop", "price" => 50000],
["item" => "Mouse", "price" => 500],
["item" => "Keyboard", "price" => 1500]
];
$total = 0;
foreach ($cart as $product) {
$total += $product["price"];
}
echo "Total Price: ₹$total";
5.2 Student Marks Example
$marks = ["Math" => 85, "Science" => 90, "English" => 78];
foreach ($marks as $subject => $score) {
echo "$subject: $score <br>";
}
6. Advantages of Using Arrays in PHP
- Efficient storage of multiple values in a single variable.
- Dynamic (can grow or shrink).
- Organized data handling with keys.
- Easier iteration with loops.
- Built-in functions for manipulation.
7. Best Practices for PHP Arrays
- Use associative arrays when working with structured data.
- Prefer multidimensional arrays for tabular or hierarchical data.
- Always check if an element exists using
isset()
before accessing. - Use
count()
instead of hardcoding lengths. - Free unused large arrays to save memory.
8. Conclusion
Arrays are one of the most powerful and essential features of PHP. They allow developers to store, manage, and manipulate data efficiently. Whether you are handling a simple list of names, a database result set, or an entire shopping cart system, arrays provide the foundation for data storage in PHP.
By mastering indexed, associative, and multidimensional arrays, along with PHP in array functions, you can significantly improve the quality and performance of your web applications.
So, whether you are a beginner learning PHP basics or a developer preparing for interviews, understanding arrays is a must-have skill to become proficient in PHP programming.
Top comments (0)