Related Tags

What are numeric arrays in PHP?

numeric arrays
arrays
php

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.

svg viewer
An example of an array

How to declare and initialize an array?

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 output
  echo $my_array1[0]."\n";
  echo $my_array2[0];
  
?> 

Accessing the elements

In order to access the elements of an array, you need to know their index value.

svg viewer

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 index
  echo $my_array1[0],"\n";
  echo $my_array1[1],"\n";
  echo $my_array1[2],"\n";
  echo $my_array1[3],"\n";
    
?> 

Length of an array

The length of an array, i.e, the number of elements present in the array can be counted using the in-built function count.

svg viewer
An example of an array

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 array
  echo "Length of the array is: ".count($my_array1);
     
?> 
RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring