Arrays in PHP

An array is a structured data type that contains a number of related data items. It is kind of like a list eg. $months = array(0,1,2,3,4,5); creates an array that contains 6 different numbers.

Each item in the array has an index number which represents its position in the array. Indexing begins from 0 which means that the first value in an array will have an index of 0, the second value will have an index of 1, the third value will have an index of 2, and so on.

This tutorial explains how to create arrays in PHP and how to add elements and view elements in arrays. You will also learn how to add more items to an existing array using the array_push function.

In the video tutorial you are also introduced to print_r and var_dump. Here are the differences between echo, print, print_r, and var_dump:

  • echo – outputs all of the parameters. It is a language construct, not a function.
  • print – is mostly the same as echo. However, print has a return value of 1 meaning it can be used in expressions whereas echo has a void return type.
  • print_r – displays information about a variable or array that is readable by humans.
  • var_dump – prints out a detailed ‘dump’ of a variable or array. A dump includes information such as the type of variable or array and its size. A dump also includes the type and size of individual elements in an array. var_dump provides more detail that print_r does. More information can be found here.

Sample PHP code:

<?php
  // create a simple array with 6 elements inside it
  $months = array('January','February','March','April','May','June');

  // use array_push to add 1 or more items to the array
  array_push($months,'July','August','September','October','November','December');

  // return the value of the twelfth element in the array
  echo $months[11];

  // display the values in the array and their key
  print_r(array_values($months));

  // display the values in the array as well as the size of the array
  // and the size of each element in the array
  var_dump(array_values($months));
?>

PHP Manual references: