In this part, we will learn about PHP arrays. Arrays are an important feature in many programming languages. It helps in keeping the information organized.
The array is an ordered collection of objects. In arrays, we group together objects that contain integers and strings. We can refer to those objects with their position. We can ask array to return back the first, the second or another object of our choice.
The array works in the same scenario as we are putting letters into their specific envelope. We can, later on, draw that later back from its envelope. The letters are arranged in a specific order in each envelope. Our letter can be empty or it contains a string, number or another letter.
There are three types of arrays in PHP.
1. Indexed arrays – Arrays having the numeric index.
2. Associative arrays – Arrays with keys and values.
3. Multidimensional arrays – Arrays containing multiple arrays.
We will discuss index array in this part.
Syntax for indexed arrays:
Let’s try a simple program to understand the concept of index arrays.
$array = array(2,4,5,6,7,8);
The output of the program will be 2.
Isn’t it interesting? Why it returns 2 as output? Below is the answer.
Here is an important factor relating to arrays. You must keep it in mind while working with arrays. Array elements are starts from 0. The first packet in an array is indexed as 0, the second packet is indexed as 1 and so on.
Here in above program, we are echoing $array, we are accessing the first object of an array with zero indexes. And it will definitely give us 2 as output.
It’s a little bit confusing. If you guys are still feeling confusion then let me know in comment section.
Here let me tell about and important function that has an important role in printing the output of an array in a readable format. The function name is print readable and it is written as print_r.
Here is simple program that will use print_r function to print a more detailed output of above program.
$array = array(2,4,5,6,7,8,);
The output of the program is given in screenshot below.
Array are many other uses. It can also be used to pull the record out of the database. We can retrieve customer records and store them in an array.
PHP 5.4 has introduced a shorter version of writing the array syntax. You guys can also try it if you feel like.
By using that shorter version of array syntax we can write the above program in following way.
$list = [2,4,5,6,7,8];
And it has the same output as above program. But it will not work with the version of PHP before PHP 5.4.
Try yourself! If you will understand the basic then it will be easy for you to deal with coding in future. The array has an extensive use in PHP.