Arrays and their Operations

In this lesson. we will learn about printing arrays and finding length of an array.

As we discussed earlier, an array is like a list of values. The simplest form of an array is indexed by an integer, and ordered by the index, with the first element lying at index 0.

To debug your code while working with arrays, it is very important to view the keys and their associated values. Accessing the length of an array can also be useful on numerous occasions.

Outputting a Structured View of Arrays #

To print an array in a readable format we use the following:

print_r($arrayName)

This will print the keys and their associated values. Run the code below to see how print_r() works.

Press + to interact
<?php
$fruits = array("Type"=>"Citrus",1=>"Orange",2=>"Grapefruit",3=>"Lemon");//initializing associative array
print_r($fruits);
?>

For detailed information about arrays, take a look at the following example.

This will print keys, their associated values’ data type (and length in parenthesis) and the value itself. Run the code below to see how var_dump() works.

Press + to interact
<?php
$fruits = array("Type"=>"Citrus",1=>"Orange",2=>"Grapefruit",3=>"Lemon");//initializing associative array
var_dump($fruits);
?>

Trying to output an array with an echo will simply print the data type instead.

Press + to interact
<?php
$fruits = array("Type"=>"Citrus",1=>"Orange",2=>"Grapefruit",3=>"Lemon");//initializing associative array
echo $fruits;
?>

Length of an Array #

The total number of elements in an array is called the length of an array. This length is dynamic and can be changed over time. We can check the length of an array using an inbuilt function count with the following syntax:

count($arrayName);
Press + to interact
<?php
$fruits = array("Type"=>"Citrus",1=>"Orange",2=>"Grapefruit",3=>"Lemon");//initializing associative array
echo "Length of \$fruits is ".count($fruits);
?>