May 11, 2021 PHP
5. Gets the length of the array - count() function
6. Traverse the array of values
There are many functions about arrays in PHP that make array operation easy.
Arrays can store multiple values in a single variable:
An array is a special variable that can store multiple values in a single variable.
If you have a list of items (ex: a list of car names), store it in a single variable, as follows:
However, what if you want to traverse the array and find a particular one? What if the array has not only 3 items but 300 items?
The solution is to create an array!
Arrays can store multiple values in a single variable, and you can access them based on keys.
In PHP, the array() function is used to create an array:
In PHP, there are three types of arrays:
There are two ways to create an array of values:
The ID key is automatically assigned (the ID key always starts at 0):
Manual allocation ID key:
The following example creates an array of values called $cars, assigns three elements to the array, and then prints a piece of text that contains the values of the array:
The count() function is used to return the length of the array (number of elements):
Traversing and printing all the values in the numeric array, you can use the for loop, as follows:
An association array is an array that uses the keys that you assign to the array.
There are two ways to create an associated array:
Or:
You can then use the specified keys in the script:
Traversing and printing all the values in the associated array, you can use the foreach loop, as follows:
Tip: The foreach syntax structure provides an easy way to traverse arrays. F oreach can only be applied to arrays and objects, and if you try to apply variables to other data types, or if you do not initialize variables, an error message is issued. There are two syntaxes:
The first format traverses a given array_expression array. In each loop, the value of the current cell is assigned to $value and the pointer inside the array moves forward one step (so the next cell will be obtained in the next loop).
The second format does the same thing, except that the key name of the current cell is assigned to the variable in each loop$key.
Multi-dimensional arrays are covered in more detail in the PHP Advanced Tutorials section.
To view the full reference manual for all array functions, please visit our PHP Array reference manual.
This reference manual provides a brief description of each function and an example of its application!