Table of Contents:
PHP Arrays – Complete Tutorial with Examples
Welcome to phponline.in, your go-to place for learning PHP step by step.
In this chapter, we will learn everything about PHP Arrays, including:
- What arrays are
- Types of arrays in PHP
- Built-in array functions
- Best practices for handling arrays
- Real-world use cases of arrays in PHP
By the end of this tutorial, you will be able to create, manipulate, and optimize arrays in PHP like a pro.
You will Learn
- Introduction to PHP Arrays
- Why Use Arrays in PHP?
- Types of Arrays in PHP
- Indexed Arrays
- Associative Arrays
- Multidimensional Arrays
- Creating Arrays in PHP
- Accessing Array Elements
- Modifying Arrays in PHP
- Looping Through Arrays
- Array Functions in PHP
- Sorting Arrays
- Searching in Arrays
- Array Length and Count
- Adding & Removing Elements
- Merging Arrays
- Splitting & Slicing Arrays
- PHP Arrays and Strings
- Arrays with Forms and User Input
- Arrays in Database Queries
- Arrays in JSON and APIs
- Multidimensional Array Deep Dive
- Nested Arrays and Loops
- Performance Tips with Arrays
- Best Practices for Using Arrays
- Common Mistakes in Arrays
- Real-World Examples of PHP Arrays
1. Introduction to PHP Arrays
An array in PHP is a special variable that can hold multiple values at once. Instead of creating separate variables for each value, we can store them in an array.
For example:
$fruit1 = "Apple";
$fruit2 = "Banana";
$fruit3 = "Orange";
Instead of writing three variables, we can use an array:
$fruits = ["Apple", "Banana", "Orange"];
2. Why Use Arrays in PHP?
Arrays are essential because they:
- Store multiple values in one variable
- Reduce code duplication
- Allow looping through values
- Work with functions and databases
- Are used in real-world PHP applications like:
- Shopping carts
- User management systems
- CMS (WordPress, Drupal)
- API data processing
3. Types of Arrays in PHP
PHP supports 3 types of arrays:
- Indexed Arrays – Use numeric indexes
- Associative Arrays – Use named keys
- Multidimensional Arrays – Arrays inside arrays
3.1 Indexed Arrays
Example:
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Red
3.2 Associative Arrays
Example:
$person = [
"name" => "Alice",
"age" => 25,
"city" => "Delhi"
];
echo $person["name"]; // Alice
3.3 Multidimensional Arrays
Example:
$students = [
["John", 20, "A"],
["Alice", 22, "B"],
["Bob", 19, "C"]
];
echo $students[0][0]; // John
4. Creating Arrays in PHP
$numbers = array(1, 2, 3, 4, 5);
$fruits = ["Mango", "Pineapple", "Apple"];
5. Accessing Array Elements
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[1]; // Banana
6. Modifying Arrays in PHP
$fruits[1] = "Grapes";
echo $fruits[1]; // Grapes
7. Looping Through Arrays
$fruits = ["Apple", "Banana", "Orange"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
8. Array Functions in PHP
PHP provides 100+ built-in array functions.
Examples:
$numbers = [1, 2, 3, 4, 5];
echo count($numbers); // 5
echo in_array(3, $numbers); // true
print_r(array_reverse($numbers));
9. Sorting Arrays
$fruits = ["Banana", "Apple", "Orange"];
sort($fruits);
print_r($fruits); // Apple, Banana, Orange
10. Searching in Arrays
$numbers = [10, 20, 30, 40];
echo array_search(30, $numbers); // 2
11. Array Length
$fruits = ["Apple", "Banana", "Orange"];
echo count($fruits); // 3
12. Adding & Removing Elements
$fruits = ["Apple", "Banana"];
array_push($fruits, "Orange");
array_pop($fruits);
13. Merging Arrays
$arr1 = ["Red", "Green"];
$arr2 = ["Blue", "Yellow"];
$merged = array_merge($arr1, $arr2);
14. Splitting & Slicing Arrays
$numbers = [1, 2, 3, 4, 5];
$slice = array_slice($numbers, 1, 3);
15. PHP Arrays and Strings
$str = "red,green,blue";
$arr = explode(",", $str);
$newStr = implode("-", $arr);
16. Arrays with Forms and User Input
if (isset($_POST['hobbies'])) {
foreach ($_POST['hobbies'] as $hobby) {
echo $hobby . "<br>";
}
}
17. Arrays in Database Queries
When fetching results from MySQL:
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
18. Arrays in JSON and APIs
$json = '{"name":"John","age":30}';
$array = json_decode($json, true);
echo $array["name"]; // John
19. Multidimensional Array Deep Dive
Example:
$marks = [
"John" => ["Math" => 90, "Science" => 85],
"Alice" => ["Math" => 95, "Science" => 80]
];
echo $marks["John"]["Math"]; // 90
20. Nested Arrays and Loops
$matrix = [
[1, 2, 3],
[4, 5, 6]
];
foreach ($matrix as $row) {
foreach ($row as $col) {
echo $col . " ";
}
echo "<br>";
}
21. Performance Tips with Arrays
- Use
foreach
instead offor
for better performance - Avoid repeated
count()
calls in loops - Use
isset()
for key checks instead ofin_array()
when possible
22. Best Practices for Arrays
- Use meaningful keys in associative arrays
- Avoid deep nesting (hard to maintain)
- Use array functions for readability
23. Common Mistakes in Arrays
- Using wrong keys
- Forgetting to check if key exists
- Mixing indexed and associative arrays unnecessarily
24. Real-World Examples of PHP Arrays
- Building a shopping cart
- Handling user sessions
- Rendering dynamic menus
- Processing form data
- Storing API responses
PHP arrays, PHP associative arrays, PHP multidimensional arrays, PHP array functions, PHP array tutorial, PHP indexed arrays, PHP foreach array, PHP array push, PHP array merge
Related topic
Frequently Asked Questions (FAQ)
Q1: What are the types of arrays in PHP?
A: Indexed arrays, associative arrays, and multidimensional arrays.
Q2: Which loop is best for arrays?
A: foreach
loop is the best for arrays.
Q3: How to check if a key exists in an array?
A: Use array_key_exists()
or isset()
.
Q4: How to convert a string to an array?
A: Use explode()
function.
Q5: How to convert an array to a string?
A: Use implode()
function.