๐ŸŽ“ A1Learner
๐Ÿ”

PHP Arrays

An array is a container that holds many values in order under one name. An index is a number that marks the place of one value in the array.

Making an array and reading one value

Square brackets make the array. Reading index 0 prints red, the first value.

<?php
$colors = ["red", "green", "blue"];
echo $colors[0] . "\n";

Changing one value

Index 1 gets a new value. Printing index 1 shows the change.

<?php
$colors = ["red", "green", "blue"];
$colors[1] = "yellow";
echo $colors[1] . "\n";

Counting the values

The colors array holds three values. The count prints as 3.

<?php
$colors = ["red", "green", "blue"];
echo count($colors) . "\n";

Printing the whole array

print_r shows each index beside its value. The indexes run from 0 to 2.

<?php
$colors = ["red", "green", "blue"];
print_r($colors);

Example

<?php
$scores = [10, 20, 30];
print_r($scores);
$total = $scores[0] + $scores[1] + $scores[2];
echo "Total: " . $total . "\n";

Key points

  • An array holds its values in order under one name.
  • Indexes start at 0.
  • Square brackets with an index read one value from an array.
  • Square brackets with an index and a new value change that value.
  • count() counts the values in an array.
  • print_r prints the whole array with its indexes.

In this example, print_r prints the scores array with its indexes. The total adds the three scores by their indexes. The last line prints that total as 60.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

What index holds the first value in an array?