Array
(PHP 4, PHP 5, PHP 7)
array- Creating a new array
Descriptionarray
array ([ mixed
$...
])
Creates an array. For information on what an array is, read the array section.
Parameters
-
...
-
The syntax "index = values", separated by commas, defines the index and value. The index can be a string or a number. If the index is omitted, an integer index starting from 0 is automatically generated. If the index is an integer, the next resulting index will be the current largest integer index + 1. Note If you define two identical indexes, the next one overwrites the previous one.
Adding a comma after the last defined array item is not common, but it is a valid syntax.
return value
Returns an array created from a parameter. Parameters can be indexed with the- = operator. For information on what an array is, read the array section.
Example
The following example shows how to create a two-dimensional array, how to assign a key name to the corresponding array, and how to skip and continue the numeric index in a normal array.
Example #1 Array () example
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
Example Automatic indexing of #2 array ()
<?php
$array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13);
print_r($array);
?>
The above routines will output:
Array ( [0] = 1 [1] = 1 [2] = 1 [3] = [4] = 1 [8] = 1 [9] = 19)
Note that index 3 is defined two times and retains the last value of 13. Index 4 is defined after index 8, and the next auto-generated index (with a value of 19) is 9 because the largest index is 8.
This example establishes an array starting with 1.
Example #3 Array () indexed starting from 1
<?php
$firstquarter = array(1 => ‘January‘, ‘February‘, ‘March‘);
print_r($firstquarter);
?>
The above routines will output:
Array ( [1] = January [2] = February [3] = March)
In Perl, you can access the value of an array within double quotation marks. But in PHP you need to enclose the array in curly braces.
Example #4 access to arrays within double quotes
<?php
$foo = array(‘bar‘ => ‘baz‘);
echo "Hello {$foo[‘bar‘]}!"; // Hello baz!
?>
Comments
Note:
Array () is a language structure that is used to literally represent an array, not a regular function.
See
- Array_pad ()-fills the array with a value to a specified length
- List ()-assigns the values in the array to some variables
- COUNT ()-Calculates the number of cells in an array or the number of attributes in an object
- Range ()-Creates an array containing the specified range of cells
- Foreach
- The array type
PHP array and array index