PHP Introduction | Values, Variables, Arrays, and Syntax | Arrays
A variable that stores a value such as a number or text can basically store only one value in one variable. However, when you need to process a lot of data, putting each piece of data into a separate variable becomes quite complex and difficult to manage. You need an easier way to handle many values.
This is when arrays and associative arrays are used. They are special variables that can handle many values at once. An array provides many containers for storing values, and each container can hold a different value.
An array is a variable that manages values by using numbers, or integers. It is created in the following form.
$variable = array(value1, value2, ...);
The values specified in () are stored in the array. They are numbered in order starting from 0, such as 0, 1, 2, and so on. This number is called an index. When you retrieve a value from an array or set a value for a specific element of an array, you specify this index number.
$variable = $array[index];
$array[index] = value;
Using the form above, you can retrieve a specific value from an array or change a value.
About Associative Arrays
Another type, the associative array, can also manage multiple values like an array. The difference from an array is that each value is managed by a name called a key, rather than by an index number. An associative array is written as follows.
$variable = array(key1 => value1, key2 => value2, ...);
As you can see, each key and its assigned value are connected with the => symbol. The values in an associative array created this way can be used in the following form.
$variable = $associativeArray[key];
$associativeArray[key] = value;
This lets you get and set the value for the specified key. Be careful, because you cannot retrieve a value unless the key exactly matches the name.
You will understand the convenience of arrays and associative arrays later when using a construct called a loop. For now, it is enough to remember that these features exist.