PHP Program to Demonstrate Arrays (most used structure in PHP)
Learn PHP step by step.
All about PHP - Arrays (most used structure in PHP)
Jan 29, 2026
## Chapter 8: Arrays (most used structure in PHP)
**Think of arrays as containers that hold multiple items - like a shopping cart or a filing cabinet!**
**Goal:** Work with lists and key/value data, because most PHP apps live on arrays.
### What Are Arrays? - PHP's Storage Containers
**Arrays let you store multiple values in one variable - like having a box that can hold many smaller boxes!**
```php
<?php
// Instead of many separate variables:
$color1 = "red";
$color2 = "green";
$color3 = "blue";
// Use one array to hold them all:
$colors = ["red", "green", "blue"];
```
**Visual Diagram: Arrays vs Individual Variables**
```
┌─────────────────────────────────────────────────────────────┐
│ Variables vs Arrays Comparison │
├─────────────────────────────────────────────────────────────┤
│ │
│ Separate Variables (Messy!) │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ $color1 │ │ $color2 │ │ $color3 │ │
│ │ "red" │ │ "green" │ │ "blue" │ │
│ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ One Array (Organized!) │
│ ┌─────────────────────────────────────────────┐ │
│ │ $colors (Array) │ │
│ │ ┌─────┐ ┌─────┐ ┌─────┐ │ │
│ │ │[0] │ │[1] │ │[2] │ │ │
│ │ │"red"│ │"grn"│ │"blu"│ │ │
│ │ └─────┘ └─────┘ └─────┘ │ │
│ └─────────────────────────────────────────────┘ │
│ │
│ **Arrays keep related data together!** │
└─────────────────────────────────────────────────────────────┘
```
### Indexed Arrays - Numbered Lists
**Indexed arrays are like numbered shelves - each item has a position starting from 0!**
```php
<?php
// Creating an indexed array
$colors = ["red", "green", "blue"];
$numbers = [10, 20, 30, 40, 50];
$names = ["Alice", "Bob", "Charlie"];
// Accessing items by their position (index)
echo $colors[0]; // Output: red
echo $colors[1]; // Output: green
echo $colors[2]; // Output: blue
// Getting array length
echo count($colors); // Output: 3
```
**Visual Diagram: Indexed Array Structure**
```
┌─────────────────────────────────────────────────────────────┐
│ Indexed Array Example │
├─────────────────────────────────────────────────────────────┤
│ │
│ Array: $colors = ["red", "green", "blue"] │
│ │
│ ┌─────┬─────┬─────┐ │
│ │ [0] │ [1] │ [2] │ ← These are the INDEXES (positions) │
│ ├─────┼─────┼─────┤ │
│ │ red │grn │ blu │ ← These are the VALUES │
│ └─────┴─────┴─────┘ │
│ │
│ **Remember: Counting starts at 0, not 1!** │
└─────────────────────────────────────────────────────────────┘
```
### Associative Arrays - Named Labels
**Associative arrays are like labeled drawers - each item has a name instead of a number!**
```php
<?php
// Creating an associative array
$user = [
"id" => 10,
"name" => "Meera",
"city" => "Jaipur",
"age" => 21
];
// Accessing items by their keys (labels)
echo $user["name"]; // Output: Meera
echo $user["city"]; // Output: Jaipur
echo $user["age"]; // Output: 21
```
**Visual Diagram: Associative Array Structure**
```
┌─────────────────────────────────────────────────────────────┐
│ Associative Array Example │
├─────────────────────────────────────────────────────────────┤
│ │
│ Array: $user = [ │
│ "id" => 10, │
│ "name" => "Meera", │
│ "city" => "Jaipur", │
│ "age" => 21 │
│ ] │
│ │
│ ┌─────────┬─────────┬─────────┬─────────┐ │
│ │ "id" │ "name" │ "city" │ "age" │ ← These are KEYS │
│ ├─────────┼─────────┼─────────┼─────────┤ │
│ │ 10 │ "Meera" │"Jaipur" │ 21 │ ← These are VALUES │
│ └─────────┴─────────┴─────────┴─────────┘ │
│ │
│ **Keys are like labels, values are what's inside!** │
└─────────────────────────────────────────────────────────────┘
```
### Real-World Array Examples
#### Example 1: Shopping Cart
```php
<?php
// Shopping cart with multiple products
$cart = [
["name" => "Laptop", "price" => 999.99, "quantity" => 1],
["name" => "Mouse", "price" => 29.99, "quantity" => 2],
["name" => "Keyboard", "price" => 79.99, "quantity" => 1]
];
// Calculate total
echo "Your cart contains:n";
foreach ($cart as $item) {
$subtotal = $item["price"] * $item["quantity"];
echo "- {$item['name']}: ${$item['price']} x {$item['quantity']} = ${$subtotal}n";
}
?>
```
#### Example 2: Student Grades
```php
<?php
// Student data with grades
$students = [
"Alice" => ["math" => 85, "science" => 92, "english" => 78],
"Bob" => ["math" => 76, "science" => 88, "english" => 91],
"Charlie" => ["math" => 93, "science" => 87, "english" => 85]
];
// Calculate average for each student
foreach ($students as $name => $grades) {
$average = array_sum($grades) / count($grades);
echo "$name's average: " . round($average, 1) . "n";
}
?>
```
#### Example 3: Blog Posts
```php
<?php
// Blog posts array
$posts = [
[
"title" => "Learning PHP",
"author" => "John Doe",
"date" => "2024-01-15",
"tags" => ["PHP", "programming", "web"],
"views" => 1250
],
[
"title" => "Arrays in PHP",
"author" => "Jane Smith",
"date" => "2024-01-20",
"tags" => ["PHP", "arrays", "data"],
"views" => 890
]
];
// Display posts
foreach ($posts as $post) {
echo "Title: {$post['title']}n";
echo "By: {$post['author']} on {$post['date']}n";
echo "Tags: " . implode(", ", $post['tags']) . "n";
echo "Views: {$post['views']}nn";
}
?>
```
### Looping Through Arrays - Visiting Each Item
**`foreach` is like visiting each item in your storage container one by one!**
```php
<?php
// Looping through indexed array
$scores = [10, 20, 30];
echo "Your scores:n";
foreach ($scores as $score) {
echo "Score: $scoren";
}
// Looping through associative array
$user = ["name" => "Meera", "age" => 21, "city" => "Jaipur"];
echo "nUser information:n";
foreach ($user as $key => $value) {
echo "$key: $valuen";
}
?>
```
### Adding and Removing Items
```php
<?php
// Adding items to arrays
$fruits = ["apple", "banana"];
$fruits[] = "orange"; // Add to end
array_push($fruits, "grape"); // Add to end
array_unshift($fruits, "kiwi"); // Add to beginning
// Removing items
array_pop($fruits); // Remove from end
array_shift($fruits); // Remove from beginning
unset($fruits[1]); // Remove specific item
// Adding to associative arrays
$user = ["name" => "John", "age" => 25];
$user["email"] = "john@example.com"; // Add new key-value pair
$user["age"] = 26; // Update existing key
?>
```
### Common Array Mistakes (And How to Fix Them!)
| Mistake | What Happens | Fix It Like This |
|---------|-------------|------------------|
| **Wrong array syntax** | Parse error | Use correct brackets: `$arr = [1,2,3]` |
| **Accessing non-existent index** | Undefined offset | Check if index exists: `isset($arr[0])` |
| **Wrong key in associative array** | Undefined index | Use correct key: `$user["name"]` not `$user[name]` |
| **Forgetting quotes around string keys** | Warning | Always quote string keys: `$arr["key"]` |
### Practice Exercises
**Try these to master arrays:**
1. **Create a Grocery List:**
```php
<?php
$groceries = ["milk", "bread", "eggs", "cheese"];
echo "Shopping list:n";
foreach ($groceries as $item) {
echo "- $itemn";
}
echo "Total items: " . count($groceries);
?>
```
2. **Create a Contact Card:**
```php
<?php
$contact = [
"name" => "[YOUR_NAME]",
"phone" => "[YOUR_PHONE]",
"email" => "[YOUR_EMAIL]"
];
echo "Contact Information:n";
foreach ($contact as $field => $value) {
echo ucfirst($field) . ": $valuen";
}
?>
```
3. **Fix This Broken Code:**
```php
<?php
$colors = ["red", "green", "blue"];
echo $colors[3]; // What's wrong here?
$user = ["name" => "John"];
echo $user[name]; // What's wrong here?
?>
```
### Array Functions Cheat Sheet
```php
<?php
// Most useful array functions
$numbers = [3, 1, 4, 1, 5, 9];
// Counting
echo count($numbers); // 6
echo sizeof($numbers); // 6 (same as count)
// Sorting
sort($numbers); // Sorts in place: [1, 1, 3, 4, 5, 9]
rsort($numbers); // Reverse sort
// Adding/removing
array_push($numbers, 2); // Add to end
array_pop($numbers); // Remove from end
array_shift($numbers); // Remove from beginning
// Searching
$position = array_search(4, $numbers);
$hasValue = in_array(5, $numbers);
// Get first/last
$first = reset($numbers);
$last = end($numbers);
?>
```
### Key Takeaways
- **Arrays hold multiple values** - like containers for related data
- **Indexed arrays use numbers** - start at 0: `$colors[0]`
- **Associative arrays use names** - like labeled boxes: `$user["name"]`
- **Use `foreach` to loop through arrays** - visit each item
- **Arrays are everywhere in PHP** - master them to build real applications
**Remember:** Arrays are PHP's way of organizing data - learn them well and you can build anything!**
### Map/filter (clean and readable)
```php
<?php
$nums = [1, 2, 3, 4, 5, 6];
$even = array_values(array_filter($nums, fn($n) => $n % 2 === 0));
$square = array_map(fn($n) => $n * $n, $even);
var_dump($square);
```
---
## Conclusion
In this article, we explored the core concepts of All about PHP - Arrays (most used structure in PHP). Understanding these fundamentals is crucial for any developer looking to master this topic.
## Frequently Asked Questions (FAQs)
**Q: What is All about PHP - Arrays (most used structure in PHP)?**
A: All about PHP - Arrays (most used structure in PHP) is a fundamental concept in this programming language/topic that allows developers to perform specific tasks efficiently.
**Q: Why is All about PHP - Arrays (most used structure in PHP) important?**
A: It helps in organizing code, improving performance, and implementing complex logic in a structured way.
**Q: How to get started with All about PHP - Arrays (most used structure in PHP)?**
A: You can start by practicing the basic syntax and examples provided in this tutorial.
**Q: Are there any prerequisites for All about PHP - Arrays (most used structure in PHP)?**
A: Basic knowledge of programming logic and syntax is recommended.
**Q: Can All about PHP - Arrays (most used structure in PHP) be used in real-world projects?**
A: Yes, it is widely used in enterprise-level applications and software development.
**Q: Where can I find more examples of All about PHP - Arrays (most used structure in PHP)?**
A: You can check our blog section for more advanced tutorials and use cases.
**Q: Is All about PHP - Arrays (most used structure in PHP) suitable for beginners?**
A: Yes, our guide is designed to be beginner-friendly with clear explanations.
**Q: How does All about PHP - Arrays (most used structure in PHP) improve code quality?**
A: By providing a standardized way to handle logic, it makes code more readable and maintainable.
**Q: What are common mistakes when using All about PHP - Arrays (most used structure in PHP)?**
A: Common mistakes include incorrect syntax usage and not following best practices, which we've covered here.
**Q: Does this tutorial cover advanced All about PHP - Arrays (most used structure in PHP)?**
A: This article covers the essentials; stay tuned for our advanced series on this topic.