PHP Arrays

An array stores multiple values in a single variable.

Syntax$fruits = ["apple", "banana", "cherry"];

An array holds many values under one name. The simplest kind is the indexed array, where each item has a numeric index starting at 0.

Create an array with square brackets [] or the array() function.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Store a list of product IDs returned from a database query in a PHP array for further processing.
  • Collect all validation error messages in an array and pass them to a view for display.
  • Use an array to accumulate totals from multiple line items before computing a cart grand total.

More examples

Creating and accessing arrays

Square-bracket syntax creates indexed arrays; $arr[] appends a new element at the next numeric index.

Example · php
<?php
$colors = ['red', 'green', 'blue'];

echo $colors[0];      // red
echo count($colors);  // 3

$colors[] = 'yellow'; // append
echo $colors[3];      // yellow

Array manipulation with push and pop

array_push() adds to the end; array_pop() removes from the end — together they implement a simple stack.

Example · php
<?php
$queue = ['task1', 'task2'];

array_push($queue, 'task3', 'task4');
$done = array_pop($queue);   // removes 'task4'

echo $done;          // task4
echo count($queue);  // 3

Checking for values and keys

in_array() tests membership; array_search() returns the key of the found element.

Example · php
<?php
$roles = ['editor', 'contributor', 'admin'];

if (in_array('admin', $roles)) {
    echo 'Admin role found';
}

$index = array_search('editor', $roles);
echo $index; // 0

Discussion

  • Be the first to comment on this lesson.