PHP ยท Chapter 20 of 44

PHP Arrays

An array is a special variable that can hold multiple values under a single name. PHP arrays can be indexed (using numeric keys) or associative (using named keys), and they can even mix different data types.

Arrays are created using the array() function or the shorter [] syntax. PHP offers many built-in functions for adding, removing, searching and transforming array elements.

Syntax
$arr = ["a", "b", "c"];
$arr[] = "d";

Indexed arrays

Indexed arrays use numeric keys starting at 0 by default. You access elements using square brackets, like $fruits[0] for the first element.

Common array functions

count() returns the number of elements, array_push() adds an element to the end, and in_array() checks whether a value exists in the array.

Example 1 (php)
<?php
  $fruits = ["apple", "banana", "cherry"];
  echo $fruits[1];
?>
Output
banana

Array indexes start at 0, so index 1 refers to the second element, "banana".

Example 2 (php)
<?php
  $nums = [1, 2, 3];
  array_push($nums, 4);
  echo count($nums);
?>
Output
4

array_push() adds a new element to the end of the array, so count() now returns 4.

Key points

  • Arrays store multiple values in a single variable.
  • Indexed arrays use numeric keys starting from 0.
  • count() returns the number of elements in an array.
  • PHP has many built-in functions for manipulating arrays.
๐Ÿ’ก Note: Use print_r($array) or var_dump($array) to inspect the full contents of an array while debugging.

๐Ÿ“ Quick Quiz

1. What index does the first element of an indexed array have?

2. Which function returns the number of elements in an array?

3. Which function adds an element to the end of an array?