Php array short syntax

Request for Comments: Short syntax for arrays

Contra: Antony Dovgal, Derick Rethans, Jani Taskinen, Lokrain, Felipe Pena, Marcus Boerger, David Soria Parra, Johannes Schlüter, Maciek Sokolewicz, Ilia Alshanetsky, Daniel Brown, Jochem Maas, Hannes Magnusson, David Coallier

Pro: Sebastian Deutsch, Ryusuke Sekiyama, Stefan Marr, Alexey Zakhlestin, Carl P. Corliss, Darius Jahandarie, Giedrius D, Eric Coleman, Max Antonov, Mike Ford, Larry Garfield, Sam Barrow, Taylor Luk, Hans Ahlin, Karoly Negyesi, Guilherme Blanco, Jonathan-Bond Caron

Note: This list was created by guessing (cvs name vs. real name) who has commit rights — please correct mistakes

This RFC will discuss an language enhancement for simple and easy array definition.

Update: May 2011

This topic has come up again on the list.

Introduction

In some cases it is necessary that you have to pass function parameters as an array. Especially when you work with nested arrays the php array function tends to make the code looking ugly. If you take a look at other languages (Ruby, Python, Javascript) there is a short syntax for arrays using square brackets. Maybe PHP should adopt this behaviour to make code more readable and maintainable.

Another solution would be to implement named parameters.

Syntax

Ryusuke suggested two possibly syntaxes and also provides two patches for a solution:

Square bracket array shortcut — keys and values are separated by colons:

$a = [1, 2, 3]; $b = ['foo': 'orange', 'bar': 'apple', 'baz': 'lemon'];

Square bracket array shortcut — keys and values are separated by double arrows:

$a = [1, 2, 3]; $b = ['foo' => 'orange', 'bar' => 'apple', 'baz' => 'lemon'];

Proposal and Patch

Pro / Contra

Pro and contra arguments that were derived from the list.

Источник

Php array short syntax

// 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.

Источник

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» )
);
?>

Пример #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 int to hour
Оцените статью