PHP Arrays

An array stores many values in one variable. Instead of creating ten variables for ten names, you can keep all names in one array. Each value in an array has a key (also called index) that you use to get it.


Types of arrays

TypeKeysExample
Indexed arrayNumbers, starting from 0[“Apple”, “Banana”]
Associative arrayNames that you choose[“name” => “Robin”, “age” => 25]
Multidimensional arrayAn array inside an array[[1, 2], [3, 4]]

Indexed array

<?php
$fruits = ["Apple", "Banana", "Cherry"];

echo $fruits[0] . "<br>";
echo $fruits[1] . "<br>";
echo count($fruits);
?>

Output:

Tutorials Class - Output Window

Apple
Banana
3

Associative array

<?php
$user = ["name" => "Robin", "age" => 25, "city" => "Delhi"];

echo $user["name"] . " lives in " . $user["city"];
?>

Output:

Tutorials Class - Output Window

Robin lives in Delhi

Multidimensional array

<?php
$students = [
    ["Robin", 25],
    ["Jenny", 23]
];

echo $students[1][0] . " is " . $students[1][1] . " years old";
?>

Output:

Tutorials Class - Output Window

Jenny is 23 years old


Add, change and remove values

<?php
$fruits = ["Apple", "Banana"];

$fruits[] = "Mango";        // add at the end
$fruits[0] = "Orange";      // change a value
unset($fruits[1]);          // remove a value

print_r($fruits);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Orange
[2] => Mango
)

After unset() the keys are not renumbered. Use array_values() if you need keys 0, 1, 2 again. There are many functions to work with arrays, see PHP Array Functions.


Loop through an array

Use foreach to read all the values. For an associative array you can get the key and the value.

<?php
$user = ["name" => "Robin", "age" => 25];

foreach ($user as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
?>

Output:

Tutorials Class - Output Window

name: Robin
age: 25


Check and print an array

  • count($arr) gives the number of values.
  • print_r($arr) and var_dump($arr) show the content of an array while testing.
  • isset($arr["key"]) checks if a key exists. See PHP isset().
  • [$a, $b] = [1, 2]; copies the values to variables (destructuring).
Note: Do not use echo $array. It prints the word “Array” and a warning. Use print_r() or a loop. Learn how to convert an array to a string.

Next chapter: PHP Array Functions.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
No Content Found.