What is PHP Arrays
Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. Let’s suppose you want to store colors in your PHP script. Storing the colors one by one in a variable could look something like this:
Example:-
An array stores multiple values in one single variable:
Example:
Create an Array in PHP
In PHP, the array() function is used to create an array:
| array(); |
But what, if you want to store the states or city names of a country in variables and this time this not just three may be hundred. It is quite hard, boring, and bad idea to store each city name in a separate variable. And here array comes into play.
Types of Arrays in PHP
There are three types of arrays that you can create. These are:
- Indexed array — An array with a numeric key.
- Associative array — An array where each key has its own specific value
- Multidimensional arrays – Arrays containing one or more arrays
Indexed Arrays
An indexed or numeric array stores each array element with a numeric index. The following examples shows two ways of creating an indexed array, the easiest way is:
Example:-
Associative Arrays
In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the following example the array uses keys instead of index numbers:
Example:-
Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or further contain array within itself and so on. An example of a multidimensional array will look something like this:
Example:-
Viewing Array Structure and Values
You can see the structure and values of an array by using one of two statements — var_dump() or print_r(). The print_r() the statement, however, gives somewhat less information. Consider the following Example:
The print_r() statement gives the following output:Array ( [0] => London [1] => Paris [2] => New York )
This output shows the key and the value for each element in the array. To get more information, use the following statement:
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals