Introduction to PHP – Getting to Know Arrays Part 1

Guest Posts Paolo Nikko Nuñal

You might be dealing with simple algebra like adding two numbers or subtracting 5 numbers using 2 or 5 variables respectively. However, if you are dealing with 500 numbers or variables, declaring them one by one is a hassle and you don't want to waste your time.

That is why arrays are here to save the day. So you might be asking what are Arrays? Simple, arrays are special variables that can hold one value at time.

Arrays in PHP are declared using the array() function. However, you must learn that there are three types of arrays that you must know, these are indexed arrays, associative arrays and multidimensional arrays.

We'll explain each arrays later on the tutorial.

The first thing we should know is how to create arrays. Creating arrays in PHP can be done in two ways. The first one is assigning them automatically like this.

   $myArray = array("John","Joseph","Jake");

From the example above we have created an array called $myArray that contains "John", "Joseph" and "Jake".

You can also create an array by manually assigning them through their index.

  $myArray[0] = "John"
  $myArray[1] = "Joseph"
  $myArray[2] = "Jake"

From the example above, it is pretty much the same as the first example that we have only, that we are assigning each value manually. The most important thing you need to know is that arrays have index in which variables are stored. Think of it as an empty egg case or a box with many containers.

------     --------    --------
$myArray = | John | Joseph | Jake |
------    ----------   --------
0            1           2

From the simple illustration above, you can see that the variable myArray contains three strings in which they have their own address called indexes.

In order for you to access each element you can also call them through their address or loop them.

    $myArray = array("John","Joseph","Jake");
    echo $myArray[0];
    echo $myArray[1];
    echo $myArray[2];

We will continue on our next tutorial on how to loop through arrays.