How To Create Indexed Arrays With PHP

How To Create Indexed Arrays With PHP

·

1 min read

In this tutorial, we will learn about indexed arrays.

What Are Indexed Arrays?

The simplest type of array is the indexed array. This means that the keys of the array are numbers. This is the default type of array: if you do not specify any particular key value, PHP will begin the first key as 0 and keep counting upwards with 1,2,3,4, etc. Declaring An Array You can declare an array in three different syntax.

<?php
$a = array("c", "a", "t");
$b = ["b", "a", "t"];
$c[0] = "r";
$c[1] = "a";
$c[2] = "t"; 
?>

The first syntax uses the "array()" function.

The second syntax uses the [] square bracket. List the values inside of [] separated with commas.

The third syntax declares the values manually.

Count() Function

A useful function for finding out the total number of units in an array is the count() function.

<?php
$a = ["a", "q", "w", "e"];
echo count($a);
?>

Result

1.png Here is how you can loop through an entire array with count().

<?php
$a = ["z", "x", "c", "v", "b"]; 
for($i=0; $i<count($a); $i++)
{
echo $a;
echo "<br>";
}
?>

Result

2.png