English
German

PHP Array

PHP 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).


PHP A Numerically Indexed Array

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.

Example:

$employee_array[0] = "B";
$employee_array[1] = "S";
$employee_array[2] = "A";
$employee_array[3] = "C";
 

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.

Note: As you may have noticed from the above code example, an array's keys start from 0 and not 1. This is a very common problem for many new programmers who are used to counting from 1 and lead to "off by 1" errors. This is just something that will take experience before you are fully comfortable with it.


PHP Associative Arrays

In an associative array a key is associated with a value. If you wanted to store the salaries of your employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

Example:

$salaries["B"] = 2000;
$salaries["S"] = 4000;
$salaries["A"] = 600;
$salaries["C"] = 0;

echo "B is being paid - $" . $salaries["B"] . "<br />";
echo "S is being paid - $" . $salaries["S"] . "<br />";
echo "C is being paid - $" . $salaries["C"] . "<br />";
echo "A is being paid - $" . $salaries["A"];
 


PHP Tutorial,PHP Array, PHP Array example, learn PHP Array,explain example PHP Array online free training PHP Tutorial, PHP Tutorial example, learn PHP Array, online tutorial, download tutorial, PHP Tutorial books, PHP Tutorial videos, live videos PHP Tutorial, learn PHP Tutorial, PHP Tutorial topic PHP Array, live training PHP Tutorial, download free tutorial