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.
$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.
<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[1];
?>bananaArray indexes start at 0, so index 1 refers to the second element, "banana".
<?php
$nums = [1, 2, 3];
array_push($nums, 4);
echo count($nums);
?>4array_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.
