PHP array() function
The array()
function in PHP is used to create an array. Arrays in PHP are versatile data structures that can hold multiple values under a single variable name. This function allows you to define both indexed and associative arrays.
Syntax:
Parameters:
- mixed $value1, $value2, ..., $valueN: A variable number of values that you want to include in the array. You can pass as many values as you like, including other arrays.
Return Value:
- The function returns an array containing the values passed as arguments.
Example 1: Creating an Indexed Array
An indexed array uses numeric keys to store values. Here's how you can create one:
Output:
Example 2: Creating an Associative Array
An associative array uses named keys that you assign to them. This allows you to access values using those keys.
Output:
Example 3: Creating a Multi-Dimensional Array
You can also create arrays within arrays, known as multi-dimensional arrays. This is useful for storing more complex data structures.
Output:
Example 4: Using array()
to Create an Empty Array
You can also create an empty array and populate it later.
Output:
Example 5: Nested Arrays
You can create nested arrays, allowing for even more complex data structures.
Output:
Summary:
- The
array()
function is a fundamental method in PHP for creating arrays, which can be indexed or associative. - You can store multiple types of data within arrays, including other arrays, allowing for complex data structures.
- Arrays are commonly used for storing lists of items, configuration options, and more, making them an essential part of PHP programming.
Note:
As of PHP 5.4, you can also use the short array syntax with square brackets to create arrays, which is often preferred for its simplicity: