Php init string array

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
)

Читайте также:  Get objects json java

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’);

Читайте также:  Визуальный редактор для html javascript

Источник

PHP String Array

In this tutorial, you shall learn how to create a string array in PHP, how to echo the string array to browser, how to iterate over individual strings of the array, etc.

PHP String Array

PHP String Array is an array in which the elements are strings.

Create String Array

You can use array() function with comma strings passed as argument to it, to create an array of strings. The syntax is

$arr = array( string1, string2, string3 );

In the following program, we will create an array containing strings as elements.

PHP Program

You can use create an empty array first using array() function and then assign strings using offset. The syntax is

$arr = array(); $arr[0] = "string1"; $arr[1] = "string2";

In the following program, we will create an empty array and then assign strings as elements to it using index/offset.

PHP Program

Echo String Array

You can use echo construct and impode() function to display all elements of string array to browser.

In the following example, we will display all elements of string array, separated by a single space.

PHP Program

Program Output

PHP String Array - Output

Iterate over elements of String Array

To iterate over individual strings of string array, you can use foreach loop, for loop, while loop, etc.

In the following example, we will use PHP foreach loop to iterate over elements of string array.

PHP Program

In the following example, we will use PHP For Loop to iterate over elements of string array.

PHP Program

In the following example, we will use PHP While Loop to iterate over elements of string array.

PHP Program

Conclusion

In this PHP Tutorial, we learned about String Arrays in PHP: how to create them, how to echo them and how to iterate over the strings in the array.

Источник

Php init string array

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

Читайте также:  Derdevicedx11 cpp 5644 createcomputeshader failed hresult 0x80070057

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.

Источник

Оцените статью