Skip to content

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.
?>

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.

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.

Keys are automatically assigned as integers, starting from 0.

<?php
// Automatic indexing (starts from 0)
$cars = ["Volvo", "BMW", "Toyota"];
echo $cars[0]; // Output: Volvo
echo $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
?>

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
?>

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
?>

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>";
}
?>

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 elements
echo $users[0]["name"]; // Output: Peter
echo $users[1]["email"]; // Output: ben@example.com
// Looping through a multidimensional array
foreach ($users as $user) {
echo "User: " . $user["name"] . ", Email: " . $user["email"] . "<br>";
}
?>

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.