Numeric arrays allow us to store multiple values of the same data type in a single variable without having to create separate variables for each value. These values can then be accessed using an index which in case of numeric arrays is always a number.
Note: By default the index always starts at zero.
There are two ways to create an array. Let’s take a look at both these ways in the example below:
<?php//creating an empty array$empty_array = array();//Method 1 to create an array$my_array1 = array("apple", "banana", "mango", "peach");//Method 2 to create an array$my_array2[0] = "joe";$my_array2[1] = "jonas";$my_array2[2] = "nick";//displaying outputecho $my_array1[0]."\n";echo $my_array2[0];?>
In order to access the elements of an array, you need to know their index value.
Let’s take a look at an example below:
<?php//Method 1 to create an array$my_array1 = array("apple", "banana", "mango", "peach");//accessing elements of array using their indexecho $my_array1[0],"\n";echo $my_array1[1],"\n";echo $my_array1[2],"\n";echo $my_array1[3],"\n";?>
The length of an array, i.e, the number of elements present in the array can be counted using the in-built function count
.
Let’s take a look at an example implementing count
:
<?php//Method 1 to create an array$my_array1 = array("apple", "banana", "mango", "peach");//calculating length of the arrayecho "Length of the array is: ".count($my_array1);?>
Free Resources