PHP Arrays
# Chapter 10: PHP Arrays
1. Introduction
Welcome to Chapter 10! As your applications grow, you need to manage collections of data—like a list of users, items in a shopping cart, or settings for a website. Creating a separate variable for every single item ($car1, $car2, $car3) is highly inefficient and impossible to scale. The solution is the Array. An array is a special, powerful variable that can hold multiple values under a single name. In this chapter, we will master Indexed Arrays, Associative Arrays, and Multidimensional Arrays.
2. Learning Objectives
By the end of this chapter, you will be able to:- Create and manipulate Indexed Arrays (lists of data).
- Create Associative Arrays (Key-Value pairs).
-
Loop through arrays effortlessly using the
foreachloop.
- Understand Multidimensional arrays (arrays inside arrays).
- Use built-in PHP array functions to sort and manage data.
3. Indexed Arrays
An indexed array stores multiple items, and each item is automatically assigned a numerical index. Important: Indexes in programming always start at 0, not 1!*Modern PHP also allows creating arrays using short syntax []:*
$fruits = ["Apple", "Banana", "Orange"];
4. Associative Arrays
Instead of numerical indexes, associative arrays use named Keys that you assign to the values. This is incredibly useful for representing structured data, like a user profile.
5. The foreach Loop
The foreach loop is specifically designed to loop through arrays. It is the most common loop you will use in PHP. It automatically knows how many items are in the array and stops when it reaches the end.
6. Multidimensional Arrays
A multidimensional array is simply an array that contains one or more arrays inside it. This is how databases return tabular data.7. Essential Array Functions
PHP has dozens of powerful built-in functions to manipulate arrays:-
count($array): Returns the number of items in the array.
-
inarray("value", $array): Checks if a value exists in an array.
-
arraypush($array, "value"): Adds a value to the end.
-
sort($array): Sorts arrays in ascending order.
8. Real-World Examples
Imagine fetching a list of links from a database to generate a website's navigation menu.*Notice the alternate PHP syntax foreach(...): and endforeach;. This is highly preferred when mixing PHP heavily with HTML blocks.*
9. Output Explanations
In the navigation example, theforeach loop extracts the Key ($title) and the Value ($url) for every item in the $navlinks array. It injects them into the href and the anchor text of the HTML, generating a complete, dynamic navigation menu.
10. Common Mistakes
-
Forgetting that indexes start at 0: Trying to access
$fruits[3]when there are 3 items will result in an "Undefined offset" warning, because the indexes are 0, 1, and 2.
-
Echoing an entire array: Writing
echo $user;will throw an error (Array to string conversion). You cannot echo an array directly. You must echo specific keys, or usevardump($user)orprintr($user)to inspect it.
-
Missing commas: When declaring arrays, items must be separated by commas
,.
11. Best Practices
-
Use descriptive plural names for arrays (e.g.,
$users,$products) to indicate they hold multiple items.
-
Use
printr($array)wrapped in HTML<pre>tags for clean, readable debugging of arrays.
12. Exercises
-
1.
Create an indexed array of 4 cities. Loop through it with
foreachand echo them in an HTML list<ul>.
- 2. Create an associative array representing a book (title, author, pages). Echo out a sentence using that data.
13. Mini Project: Product List System
Task: Build an e-commerce product display. Use a multidimensional array to store 3 products (name, price, stock). Loop through the products and display them in HTML cards.14. Coding Challenges
Challenge 1: Create an array of numbers[10, 20, 30, 40]. Write a foreach loop that adds all the numbers together and stores the sum in a variable. Echo the final sum.
15. MCQs with Answers
1. What is the index of the first element in an indexed PHP array? A) 1 B) 0 C) -1 D) First *Answer: B*2. Which loop is specifically designed to iterate over arrays? A) for B) while C) do...while D) foreach *Answer: D*
3. What does an Associative Array use instead of numerical indexes? A) Objects B) Key-Value pairs C) Classes D) Functions *Answer: B*
16. Interview Questions
Q: What is a Multidimensional array? *A:* A multidimensional array is an array that contains one or more arrays as its values. It is used to store complex, structured data, such as a table of database records where each row is an array, and the entire table is stored inside a parent array.Q: Why shouldn't you use a for loop to iterate over an associative array?
*A:* A standard for loop relies on an integer counter ($i = 0, 1, 2) to access elements by numerical index. Associative arrays use string keys (like "name" or "email"), so $array[$i] will not work. The foreach loop gracefully handles string keys.
17. FAQs
Q: Can I mix data types inside a single array? *A:* Yes. In PHP, an array can simultaneously hold strings, integers, booleans, and even other arrays!18. Summary
You have mastered data collection! You learned how to group simple data into Indexed Arrays, structure profile-like data into Associative Arrays, and build complex datasets using Multidimensional Arrays. You also unlocked theforeach loop, an essential tool for dynamically rendering data to the screen.