The array is an important component in PHP. In arrays, a single value stores multiple values of the same nature or type. For instance, there is no need to create 50 variables if you need to store 50 different values. You will simply create one array having 50 values.
There are two main types of arrays in PHP, the Numeric Array and the Associative Array. We will study Numeric Array first.
Numeric arrays can store anything including objects, strings, and numbers. However, it is the numbers that define their index. The index in the array always starts with zero by default.
Creating an array is also super easy. As it stores values, it is basically a variable. In fact, we assign an array() function to a variable to create an array. Subsequently, we assign different values to the array function.
<?php $numList = array (2 , 3 , 4 , 5 , 6, "this is an array"); ?>
You have created your array. Now, how do you access the values from the array? We have already discussed that arrays have indexes with the first value having an index of 0. So here is how you display values in an array.
<?php $numList = array ("my array", 2 , 3 , 4 , 5 , 6, "this is an array"); echo $numList; ?>
The $numlist will display the first value of the array that is “my array.” Similarly, you will use the index numbers of 1, 2 3, and 4 and to access other values.
In fact, you can check the index number of each value by using the built-in print_r() function.
<?php $numList = array (2 , 3 , 4 , 5 , 6, "this is an array"); Print_r($numList); ?>
The above code will give you all the indexes in an array as shown in the following figure.
Associative arrays are very much similar to the Numeric arrays. The only difference is that they do not need to be ordered as their numeric counterparts. In Numeric arrays, we need to remember the index number of each value to print it. Imagine if we have 1000 values in an array. It will be next to impossible to remember the specific number of every value. This is where associative arrays come to your rescue as they can be called by their names or labels.
The process of creating an associative array is somewhat different from numeric arrays. You first write the label of the value in the quotation marks followed by a => sign. Subsequently. You place the actual value in quotations. Check the following example.
<?php $name = array("first_name" => "Jose", "second_name" => "David" , "third_name" => "Stacy"); ?>
Now, if you want to display the third value in the array, you will simply the write the following code. And, you will get Stact as an output.
<?php $name = array("first_name" => "Jose", "second_name" => "David" , "third_name" => "Stacy"); echo $name["third_name"]; ?>
Here is the output.
In the next lesson, we will have a look at the PHP comparison and logical operators.