In this tutorial, we will explore how we can use the array() method in PHP to create an index array and assign elements to it.
In PHP, an array is a data structure that can hold an ordered list of values. It is a composite data type that allows you to store multiple values of the same data type under a single variable name.
Under the hood, an array in PHP is an ordered map. A map is an associative data type that stores keys mapped to a given value.
PHP Declare Array Using the Array() Function
array() function in PHP is a built-in function that allows us to create an array. It can take zero or more comma-separated values as arguments and return an array containing those values.
The following shows the syntax of the
array() method in PHP.
array(mixed ...$values): array
values as the parameter. You can have single values separated by a list or a
index => values elements separated by a comma.
It is good to keep in mind that if the index of the elements in the array is omitted, the function will automatically generate the indexes starting at index
If the starting index is provided, the next index generated will be the biggest integer index + 1
Function Return Value
The function will return an array of the provided parameters. The parameters can be given an index using the
The following example shows how to use the
array() function in PHP to create a simple array.
$myArray = array('MySQL', 'PostgreSQL', 'SQL Server');
In this example, we are creating an array with three elements of
As mentioned, we can also use the
array() function to create an associative array where each element is identified by a key. We can pass the key value pairs to the function as shown in the example below:
$databases = array( 'MySQL' => 3306, 'PostgreSQL' => 5432, 'SQL Server' => 1433 );
In this case, we create an associative array with three key-value pairs. The keys are the names of the databases while the values are the corresponding port for each.
The following example also demonstrates how to use the
array() function to create a 1-index based array.
<?php $db = array(1 => 'MySQL', 'PostgreSQL', 'SQL Server'); ?>
And there you have it, a way to create arrays in PHP using the
array() function is a language construct used to represent literal arrays, and not a regular function.
We can also use the
array() method to create a multi-dimensional array in PHP. We can do this by nesting one or more arrays inside another array.
An example of a 2d array using the array function is as shown:
$myArray = array( array('apple', 'banana', 'cherry'), array('red', 'yellow', 'black'), array(1, 2, 3) );
In this post, we explored how we can create a literal and associative arrays using the
array() function in PHP.
We hope you enjoyed this post, leave us a comment down below, share and subscribe.