What is an Array ?

The most inconvenient thing about a variable in programming is that you can only store one value at a time. Arrays are special types that allow variables to overcome this limitation, so you can store as many values as you want in the same variable. For example, instead of having two variables “$number1” and “$number2”, you could have an array “$numbers” that will hold both values. Imagine the same thing with ten numbers. What about a hundred ? Because of the flexibility of the array, it can store two values or two hundred values, without having to define other variables.

In other words instead of having many similar variables, you can store the data as elements in an array. An array is a data structure that stores one or more values in a single value. For experienced programmers it is important to note that PHP’s arrays are actually maps (each key is mapped to a value). The PHP language indexes all the values within an array using a number or a string, so you will know which of the values you’re using.

Each element in the array has its own ID so that it can be easily accessed.

There are three different kind of arrays:

* Numeric array - An array with a numeric ID key
* Associative array - An array where each ID key is associated with a value
* Multidimensional array - An array containing one or more arrays

Numeric Arrays

A numeric array stores each element with a numeric ID key. If this is your first time seeing an array, then you may not quite understand the concept of an array. Imagine that you own a business and you want to store the names of all your employees in a PHP variable. How would you go about this ?

It wouldn’t make much sense to have to store each name in its own variable. Instead, it would be nice to store all the employee names inside of a single variable. This can be done, and we show you how below.

<?php
 
$emp[0] = "Henry";
$emp[1] = "Anna";
$emp[2] = "Paddy";
$emp[3] = "Rommy";
 
?>

In the above example we made use of the key / value structure of an array. The keys were the numbers we specified in the array and the values were the names of the employees. Each key of an array represents a value that we can manipulate and reference. The general form for setting the key of an array equal to a value is:

 $array[key] = value;

If we wanted to reference the values that we stored into our array, the following PHP code would get the job done.

<?php
 
echo "employees set 1 " . $emp[0] . " & " . $emp[1]; 
echo "<br />employees set 2"  . $emp[2] . " & " . $emp[3];
 
?>

The code above will output:

employees set 1 Henry & Anna
employees set 2 Paddy & Rommy

PHP arrays are quite useful when used in conjunction with loops, which we will discuss later on. Above we showed an example of an array that made use of integers for the keys (a numerically indexed array). However, you can also specify a string as the key, which is referred to as an associative array.



Pages : 1 2