Arrays in PHP – Storing Multiple Values
What is an Array in PHP?
An array in PHP is a data structure used to store multiple values in a single variable. Instead of creating separate variables for each value, arrays group them together — which makes code more organized and scalable.
For example:
$language1 = "PHP";
$language2 = "JavaScript";
$language3 = "Python";
This can be replaced by:
$languages = ["PHP", "JavaScript", "Python"];
Types of Arrays in PHP
1. Indexed Arrays
Arrays with numeric keys (starting at 0).
2. Associative Arrays
Arrays where keys are named (strings instead of numbers).
3. Multidimensional Arrays
Arrays that contain other arrays inside them.
1. Indexed Arrays in PHP
Creating an Indexed Array:
$colors = array("Red", "Green", "Blue");
or (short syntax):
$colors = ["Red", "Green", "Blue"];
Accessing Elements:
echo $colors[0]; // Output: Red
Looping Through:
foreach ($colors as $color) {
echo "$color<br>";
}
2. Associative Arrays in PHP
Associative arrays use key-value pairs instead of numeric indexes.
Creating an Associative Array:
$user = [
"name" => "Jay",
"email" => "jay@example.com",
"age" => 28
];
Accessing Elements:
echo $user["email"]; // Output: jay@example.com
Looping Through:
foreach ($user as $key => $value) {
echo "$key: $value<br>";
}
3. Multidimensional Arrays in PHP
A multidimensional array holds one or more arrays inside another.
Example:
$students = [
["Alice", "PHP", 85],
["Bob", "Python", 90],
["Charlie", "Java", 78]
];
echo $students[1][0]; // Output: Bob
You can also loop through them using nested loops:
foreach ($students as $student) {
echo "Name: " . $student[0] . ", Subject: " . $student[1] . ", Score: " . $student[2] . "<br>";
}
Useful Array Functions in PHP
Function | Description | Example |
---|---|---|
count() | Returns number of elements | count($colors) |
array_push() | Adds to the end | array_push($colors, "Yellow") |
array_pop() | Removes from the end | array_pop($colors) |
array_shift() | Removes first element | array_shift($colors) |
array_unshift() | Adds to beginning | array_unshift($colors, "Pink") |
in_array() | Checks if value exists | in_array("Red", $colors) |
array_key_exists() | Checks if key exists | array_key_exists("name", $user) |
implode() | Converts array to string | implode(", ", $colors) |
explode() | Converts string to array | explode(",", "PHP,HTML,CSS") |
Real-World Examples
Example 1: Creating a Dropdown from Array
$languages = ["PHP", "JavaScript", "Python"];
echo "<select>";
foreach ($languages as $lang) {
echo "<option>$lang</option>";
}
echo "</select>";
Example 2: Display Table from Array
$products = [
["Laptop", 50000],
["Mouse", 500],
["Keyboard", 800]
];
echo "<table border='1'>";
echo "<tr><th>Product</th><th>Price</th></tr>";
foreach ($products as $product) {
echo "<tr><td>{$product[0]}</td><td>{$product[1]}</td></tr>";
}
echo "</table>";
Common Mistakes with Arrays
- Using the wrong index (e.g., accessing
$arr[5]
when it only has 3 items) - Forgetting quotes around associative keys (
$user[name]
vs$user["name"]
) - Mixing indexed and associative structures without clear logic
- Not checking if a key exists before using it
Best Practices
- Use short syntax (
[]
) for cleaner code - Always check for key existence with
isset()
orarray_key_exists()
- Loop with
foreach
instead offor
unless index is needed - Keep array keys consistent (all strings or all integers)
- Use meaningful keys in associative arrays (e.g.,
"price"
,"status"
)
Notes:
- Arrays in PHP help store and manage multiple related values
- Use indexed arrays for lists, associative arrays for labeled data, and multidimensional arrays for table-like data
- PHP offers many built-in functions to manipulate arrays easily
- Always use
foreach
for clean and efficient array iteration
Practice Tasks
Task 1: Favorite Movies
Create an indexed array with 5 favorite movies. Use a loop to display them in an unordered list (<ul>
).
Task 2: User Profile
Create an associative array with:
- Name
- Age
- Country
Print each field with its label.
Task 3: Class Scores Table
Create a 2D array for 3 students:
- Each student has name, subject, score
Display in an HTML table using a nested loop.
💡 Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.