PHP Arrays
PHP Arrays
Section titled “PHP Arrays”An array is a fundamental data structure in PHP that allows you to store multiple values in a single variable.
Imagine needing to store a list of car names. Without arrays, you might do this:
<?php$car1 = "Volvo";$car2 = "BMW";$car3 = "Toyota";?>This becomes impractical if you have hundreds of cars or need to perform operations on the list, like searching or sorting. Arrays solve this problem.
<?php// Using the modern short array syntax []$cars = ["Volvo", "BMW", "Toyota"];
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";// Output: I like Volvo, BMW and Toyota.?>What is an Array?
Section titled “What is an Array?”An array is an ordered map. A map is a type that associates values to keys. PHP arrays are extremely versatile:
- They can store values of different types (integers, strings, booleans, objects, even other arrays).
- Keys can be integers (for indexed arrays) or strings (for associative arrays).
- They are dynamic, meaning you can easily add or remove elements.
Creating Arrays in PHP
Section titled “Creating Arrays in PHP”The modern and recommended way to create an array is using the short array syntax []. The older array() syntax still works but is less common in new code.
PHP supports several types of arrays:
- Indexed arrays: Arrays with numeric keys (usually starting from 0).
- Associative arrays: Arrays where keys are named strings.
- Multidimensional arrays: Arrays containing other arrays.
PHP Indexed Arrays
Section titled “PHP Indexed Arrays”Keys are automatically assigned as integers, starting from 0.
<?php// Automatic indexing (starts from 0)$cars = ["Volvo", "BMW", "Toyota"];
echo $cars[0]; // Output: Volvoecho $cars[1]; // Output: BMW
// You can also assign indices manually (less common for sequential lists)$colors = [];$colors[0] = "Red";$colors[1] = "Green";$colors[2] = "Blue";
echo $colors[1]; // Output: Green?>PHP Associative Arrays
Section titled “PHP Associative Arrays”Use named string keys to access values. This is useful for representing structured data like records or dictionaries.
<?php// Using string keys$age = [ "Peter" => 35, "Ben" => 37, "Joe" => 43];
echo "Peter is " . $age["Peter"] . " years old."; // Output: Peter is 35 years old.
// Alternative assignment$config = [];$config['database'] = 'my_db';$config['user'] = 'admin';
echo $config['database']; // Output: my_db?>Getting the Size of an Array: count()
Section titled “Getting the Size of an Array: count()”The count() function returns the number of elements in an array.
<?php$cars = ["Volvo", "BMW", "Toyota"];echo count($cars); // Output: 3
$age = ["Peter" => 35, "Ben" => 37, "Joe" => 43];echo count($age); // Output: 3?>Looping Through Arrays
Section titled “Looping Through Arrays”Indexed Arrays (using for loop):
Useful when you need the index number.
<?php$cars = ["Volvo", "BMW", "Toyota"];$arrlength = count($cars);
for ($x = 0; $x < $arrlength; $x++) { echo "Car index $x: " . $cars[$x] . "<br>";}?>Indexed and Associative Arrays (using foreach loop):
The foreach loop is generally preferred as it’s simpler and works seamlessly with both indexed and associative arrays.
<?php// Looping through an indexed array (getting values only)$colors = ["Red", "Green", "Blue"];foreach ($colors as $color) { echo "Color: $color <br>";}
// Looping through an associative array (getting keys and values)$age = ["Peter" => 35, "Ben" => 37, "Joe" => 43];foreach ($age as $name => $years) { echo "$name is $years years old.<br>";}?>Multidimensional Arrays
Section titled “Multidimensional Arrays”Arrays can contain other arrays, creating multidimensional structures, useful for representing tables or matrices.
<?php$users = [ ["name" => "Peter", "email" => "peter@example.com", "active" => true], ["name" => "Ben", "email" => "ben@example.com", "active" => false], ["name" => "Joe", "email" => "joe@example.com", "active" => true]];
// Accessing elementsecho $users[0]["name"]; // Output: Peterecho $users[1]["email"]; // Output: ben@example.com
// Looping through a multidimensional arrayforeach ($users as $user) { echo "User: " . $user["name"] . ", Email: " . $user["email"] . "<br>";}?>Common Array Operations
Section titled “Common Array Operations”PHP provides a rich set of functions for manipulating arrays:
array_push($array, $value1, ...)or$array[] = $value: Add elements to the end.unset($array[$key]): Remove an element.in_array($needle, $haystack): Check if a value exists.array_key_exists($key, $array): Check if a key exists.array_merge($array1, $array2, ...): Merge arrays.array_keys($array): Get all keys.array_values($array): Get all values.sort($array),rsort($array),asort($array),ksort($array), etc.: Various sorting functions.
Consult the official PHP documentation for a comprehensive list and examples.