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
foreachinstead offorfor 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.