Working with Arrays in PHP
A concise guide to creating, manipulating, and looping through arrays in PHP , perfect for beginners and intermediate developers.
📌 What Is an Array?
An array is a data structure that allows you to store multiple values in a single variable. PHP supports different types of arrays for various use cases.
🔢 Types of Arrays in PHP
- Indexed Arrays: Numeric index (e.g.,
$colors[0]
) - Associative Arrays: Named keys (e.g.,
$person['name']
) - Multidimensional Arrays: Arrays within arrays
✍️ Creating Arrays
<?php
$colors = ["red", "green", "blue"];
$person = ["name" => "Alice", "age" => 30];
$matrix = [[1, 2], [3, 4]];
?>
📥 Accessing Array Elements
Use the key or index to access a value:
<?php
echo $colors[1]; // green
echo $person["name"]; // Alice
?>
🛠️ Modifying Arrays
<?php
$colors[] = "yellow"; // Add to end
$person["email"] = "[email protected]"; // Add key-value pair
unset($colors[0]); // Remove first item
?>
🔁 Looping Through Arrays
<?php
foreach ($colors as $color) {
echo $color . " <br>";
}
foreach ($person as $key => $value) {
echo "$key: $value <br>";
}
?>
⚙️ Useful Array Functions
count($array)
– Get number of elementsarray_merge($a, $b)
– Merge two arraysarray_keys($array)
– Get all keysin_array("value", $array)
– Check if value existssort($array)
– Sort indexed arrayksort($array)
– Sort associative array by key
📚 Working with Multidimensional Arrays
<?php
$students = [
["name" => "John", "grade" => 90],
["name" => "Jane", "grade" => 85]
];
foreach ($students as $student) {
echo $student["name"] . ": " . $student["grade"] . "<br>";
}
?>
✅ Best Practices
- Use descriptive keys in associative arrays
- Check existence with
isset()
orarray_key_exists()
- Initialize arrays before appending
- Use
foreach
instead offor
for associative arrays
Tags: PHP arrays, array functions PHP, associative array PHP
📘 Next up: Learn how to handle forms and user input with PHP securely and effectively.