PHP Arrays
An array can store multiple values in a single variable:
Examples
Run example »
What is an array?
An array is a special variable that can store multiple values in a single variable.
If you have a list of items (for example: a list of car names), storing them in a single variable would look like this:
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the array and find a specific one? What if the array has not just 3 items but 300 items?
The solution is to create an array!
An array can store multiple values in a single variable, and you can access the values in it according to keys.
Creating arrays in PHP
In PHP, the array() function is used to create an array:
In PHP, there are three types of arrays:
- Numeric array- An array with numeric ID keys
- Associative array- An array with specified keys, each key associated with a value
- Multidimensional array- An array that contains one or more arrays
PHP Numeric Arrays
There are two ways to create numeric arrays:
Automatically assigned ID keys (ID keys always start from 0):
Manually assigned ID keys:
$cars[1]="BMW";
$cars[2]="Toyota";
The example below creates a numeric array named $cars, assigns three elements to the array, and then prints a piece of text containing the array values:
Example
Run example »
Get the length of an array - count() function
The count() function is used to return the length of an array (the number of elements):
Traversing numeric arrays
To traverse and print all values in a numeric array, you can use a for loop, as shown below:
Example
Run example »
PHP Associative Arrays
An associative array is an array that uses specified keys that you assign to the array.
There are two ways to create associative arrays:
or:
$age['Ben']="37";
$age['Joe']="43";
You can then use the specified keys in the script:
Example
Run example »
Traversing associative arrays
To traverse and print all values in an associative array, you can use a foreach loop, as shown below:
Example
Run example »
Multidimensional arrays
Multidimensional arraysThis will be introduced in detail in the PHP Advanced Tutorial section.
Complete PHP Array Reference Manual
To view the complete reference manual for all array functions, please visit ourPHP Array Reference Manual。
This reference manual provides a brief description and application examples for each function!
Other extensions