Indexed Arrays

Work with list-like arrays: iteration, inserts/removals, and common patterns.

On this page

Creating Indexed Arrays

Indexed arrays behave like ordered lists. Keys are numeric (0, 1, 2...) and usually implicit.

<?php
$tags = ['php', 'mysql', 'security'];
echo $tags[1]; // mysql

Adding Items

Use [] to append. Use array_push for multiple values (but [] is often clearer).

<?php
$tags[] = 'performance';
array_push($tags, 'devops', 'testing');

Removing Items

unset removes an element but does not automatically reindex. If you need a clean list again, reindex with array_values.

<?php
$numbers = [10, 20, 30, 40];

unset($numbers[1]);          // removes 20
print_r($numbers);           // keys: 0,2,3

$numbers = array_values($numbers); // reindex
print_r($numbers);

Iterating Lists

foreach is the most common way to iterate. Prefer it over index-based loops for readability.

<?php
foreach ($tags as $tag) {
  echo $tag . PHP_EOL;
}

Common List Patterns

Use built-in helpers to avoid manual loops when possible.

<?php
$prices = [100, 250, 80];

$total = array_sum($prices);
$count = count($prices);
$hasCheap = in_array(80, $prices, true);

var_dump($total, $count, $hasCheap);

Production Tip

When a list comes from request data or DB, validate type and shape before processing. Avoid assuming “it is always a list of strings” unless you enforce it.