array
Создаёт массив. Подробнее о массивах читайте в разделе Массивы.
Список параметров
Синтаксис «индекс => значения», разделённые запятыми, определяет индексы и их значения. Индекс может быть строкой или целым числом. Если индекс опущен, будет автоматически сгенерирован числовой индекс, начиная с 0. Если индекс — число, следующим сгенерированным индексом будет число, равное максимальному числовому индексу + 1. Обратите внимание, что если определены два одинаковых индекса, последующий перезапишет предыдущий.
Наличие завершающей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.
Возвращаемые значения
Возвращает массив параметров. Параметрам может быть назначен индекс с помощью оператора => . Подробнее о массивах читайте в разделе Массивы.
Примеры
Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.
Пример #1 Пример использования array()
$fruits = array (
«fruits» => array( «a» => «orange» , «b» => «banana» , «c» => «apple» ),
«numbers» => array( 1 , 2 , 3 , 4 , 5 , 6 ),
«holes» => array( «first» , 5 => «second» , «third» )
);
?>?php
Пример #2 Автоматическая индексация с помощью array()
Результат выполнения данного примера:
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 13 [4] => 1 [8] => 1 [9] => 19 )
Обратите внимание, что индекс ‘3’ определён дважды, и содержит последнее значение 13. Индекс 4 определён после индекса 8, и следующий сгенерированный индекс (значение 19) — 9, начиная с максимального индекса 8.
Этот пример создаёт массив, нумерация которого начинается с 1.
Пример #3 Пример использования array() , нумерация которого начинается с 1
Результат выполнения данного примера:
Array ( [1] => January [2] => February [3] => March )
Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.
Пример #4 Доступ к массиву внутри двойных кавычек
$foo = array( ‘bar’ => ‘baz’ );
echo «Hello < $foo [ 'bar' ]>!» ; // Hello baz!
Примечания
Замечание:
array() — языковая конструкция, используемая для представления литеральных массивов, а не обычная функция.
Смотрите также
- array_pad() — Дополнить массив определённым значением до указанной длины
- list() — Присваивает переменным из списка значения подобно массиву
- count() — Подсчитывает количество элементов массива или Countable объекте
- range() — Создаёт массив, содержащий диапазон элементов
- foreach
- Тип массив
User Contributed Notes 38 notes
As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.
Example #1 ‘short syntax array’
$a = [ 1 , 2 , 3 , 4 ];
print_r ( $a );
?>
The above example will output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Example #2 ‘short syntax associative array’
$a = [ ‘one’ => 1 , ‘two’ => 2 , ‘three’ => 3 , ‘four’ => 4 ];
print_r ( $a );
?>
The above example will output:
Array
(
[one] => 1
[two] => 2
[three] => 3
[four] => 4
)
an array can execute code.
i try this on php 7.4 (xampp version)
$msg = ‘HI GUYS !’
,print ( $msg )
,(function()use ( $msg ) print ‘here is php’ ;
>)()
,print ‘ I`m just an array ,alive one’
];
The following function (similar to one above) will render an array as a series of HTML select options (i.e. ««). The problem with the one before is that there was no way to handle , so this function solves that issue.
function arrayToSelect($option, $selected = », $optgroup = NULL)
$returnStatement = »;
if (isset($optgroup)) foreach ($optgroup as $optgroupKey => $optgroupValue) $returnStatement .= »;
So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of «» elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.
$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);
$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);
$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);
Php arrays as array index
// Before php 5.4
$array = array(1,2,3);
// since php 5.4 , short syntax
$array = [1,2,3];
// I recommend using the short syntax if you have php version >= 5.4
Used to creating arrays like this in Perl?
Looks like we need the range() function in PHP:
$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>
You don’t need to array_merge if it’s just one range:
There is another kind of array (php>= 5.3.0) produced by
$array = new SplFixedArray(5);
Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.
Supposing a large string-keyed array
$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]
when getting the keyed data with
php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.
However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :
Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23
but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );
(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
This function makes (assoc.) array creation much easier:
function arr (. $array )< return $array ; >
?>
It allows for short syntax like:
$arr = arr ( x : 1 , y : 2 , z : 3 );
?>
Instead of:
$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>
Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.
PHP Indexed Arrays
The index can be assigned automatically (index always starts at 0), like this:
or the index can be assigned manually:
The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:
Example
$cars = array(«Volvo», «BMW», «Toyota»);
echo «I like » . $cars[0] . «, » . $cars[1] . » and » . $cars[2] . «.»;
?>?php
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example
$cars = array(«Volvo», «BMW», «Toyota»);
$arrlength = count($cars);
?php
Complete PHP Array Reference
For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!
PHP Exercises
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.