Lecture
Arrays are ordered data sets representing a list of similar elements.
There are two types of arrays that differ in the way elements are identified.
1. In arrays of the first type, the element is determined by the index in the sequence. Such arrays are called simple arrays.
2. Arrays of the second type have an associative nature, and for accessing elements, keys are used that are logically associated with values. Such arrays are called associative arrays.
An important feature of PHP is that PHP, unlike other languages, allows you to create arrays of any complexity directly in the body of the program (script).
Arrays can be like one dimensional so and multidimensional .
When accessing items simple indexed arrays an integer index is used to determine the position of the specified element.
Simple one-dimensional arrays :
The generalized syntax of the elements of a simple one-dimensional array:
$имя
[
индекс
];
Arrays whose indexes are numbers starting with zero are lists :
<? php
// Простой способ инициализации массива
$ name s[ 0 ]= "Апельсин" ;
$ names [ 1 ]= "Банан" ;
$ names [ 2 ]= "Груша" ;
$ names [ 3 ]= "Помидор" ;
// Здесь: names - имя массива, а 0, 1, 2, 3 - индексы массива
?>
Access to the elements of simple arrays (lists) is as follows:
<? php
// Простой способ инициализации массива
$ names [ 0 ]= "Апельсин" ;
$ names [ 1 ]= "Банан" ;
$ names [ 2 ]= "Груша" ;
$ names [ 3 ]= "Помидор" ;
// Здесь: names - имя массива, а 0, 1, 2, 3 - индексы массива
// Выводим элементы массивов в браузер:
echo $ names [ 0 ]; // Вывод элемента массива names с индексом 0
echo "<br>" ;
echo $ names [ 3 ]; // Вывод элемента массива names с индексом 3
// Выводит:
// Апельсин
// Помидор
?>
From a technical point of view, there is no difference between simple arrays and lists.
Simple arrays can be created without specifying the index of a new array element; PHP will do this for you. Here is an example:
<? php
// Простой способ инициализации массива, без указания индексов
$ names []= "Апельсин" ;
$ names []= "Банан" ;
$ names []= "Груша" ;
$ names []= "Помидор" ;
// PHP автоматически присвоит индексы элементам массива, начиная с 0
// Выводим элементы массивов в браузер:
echo $ names [ 0 ]; // Вывод элемента массива names с индексом 0
echo "<br>" ;
echo $ names [ 3 ]; // Вывод элемента массива names с индексом 3
// Выводит:
// Апельсин
// Помидор
?>
In the above example, you can add elements of the names array in a simple way, that is, without specifying the index of the array element:
$names[]="Яблоко";
A new element of a simple array (list) will be added to the end of the array. In the future, with each new element of the array, the index will increase by one.
Simple multidimensional arrays :
The generalized syntax of the elements of a multidimensional simple array is:
$имя[индекс1][индекс2]..[индексN];
An example of a simple multi-dimensional array:
<? php
// Многомерный простой массив:
$ arr [ 0 ][ 0 ]= "Овощи" ;
$ arr [ 0 ][ 1 ]= "Фрукты" ;
$ arr [ 1 ][ 0 ]= "Абрикос" ;
$ arr [ 1 ][ 1 ]= "Апельсин" ;
$ arr [ 1 ][ 2 ]= "Банан" ;
$ arr [ 2 ][ 0 ]= "Огурец" ;
$ arr [ 2 ][ 1 ]= "Помидор" ;
$ arr [ 2 ][ 2 ]= "Тыква" ;
// Выводим элементы массива:
echo "<h3>" .$ arr [ 0 ][ 0 ]. ":</h3>" ;
for ($ q = 0 ; $ q <= 2 ; $ q ++) {
echo $ arr [ 2 ][$ q ]. "<br>" ;
}
echo "<h3>" .$ arr [ 0 ][ 1 ]. ":</h3>" ;
for ($ w = 0 ; $ w <= 2 ; $ w ++) {
echo $ arr [ 1 ][$ w ]. "<br>" ;
}
?>
In PHP, an array index can be not only a number, but also a string. And no restrictions are imposed on such a string: it can contain spaces, the length of such a string can be any.
Associative arrays are especially convenient in situations where it is more convenient to associate elements of an array with words rather than numbers.
So, arrays whose indexes are strings are called associative arrays .
One-dimensional associative arrays :
One-dimensional associative arrays contain only one key (element) corresponding to a specific index of an associative array. Let's give an example:
<? php
// Ассоциативный массив
$ names [ "Иванов" ]= "Иван" ;
$ names [ "Сидоров" ]= "Николай" ;
$ name s[ "Петров" ]= "Петр" ;
// В данном примере: фамилии - ключи ассоциативного массива
// , а имена - элементы массива names
?>
The access to the elements of one-dimensional associative arrays is the same as to the elements of ordinary arrays, and is called key access :
echo $names["Иванов"];
Multidimensional associative arrays :
Multidimensional associative arrays can contain several keys that correspond to a specific index of an associative array. Consider an example of a multidimensional associative array:
<? php
// Многомерный массив
$ A [ "Ivanov" ] = array ( "name" => "Иванов И.И." , "age" => "25" , "email" => " ivanov@mail.ru " );
$ A [ "Petrov" ] = array ( "name" => "Петров П.П." , "age" => "34" , "email" => " petrov@mail.ru " );
$ A [ "Sidorov" ] = array ( "name" => "Сидоров С.С." , "age" => "47" , "email" => " sidorov@mail.ru " );
?>
Multidimensional arrays are similar to Pascal entries or C structures.
Access to the elements of a multidimensional associative array is as follows:
echo $A["Ivanov"]["name"]; // Выводит Иванов И.И.
echo $A["Petrov"]["email"]; // Выводит petrov@mail.ru
As you have already noticed, to create a multidimensional associative array, we used the special function array , we will consider it later, when we consider operations on arrays .
Associative multidimensional arrays can be created in the classical way, although it is not so convenient:
<? php
// Многомерный ассоциативный массив
$ A [ "Ivanov" ][ "name" ]= "Иванов И.И." ;
$ A [ "Ivanov" ][ "age" ]= "25" ;
$ A [ "Ivanov" ][ "email" ]= " ivanov@mail.ru " ;
$ A [ "Petrov" ][ "name" ]= "Петров П.П." ;
$ A [ "Petrov" ][ "age" ]= "34" ;
$ A [ "Petrov" ][ "email" ]= " petrov@mail.ru " ;
$ A [ "Sidorov" ][ "name" ]= "Сидоров С.С." ;
$ A [ "Sidorov" ][ "age" ]= "47" ;
$ A [ "Sidorov" ][ "email" ]= " sidorov@mail.ru " ;
// Получаем доступ к ключам многомерного ассоциативного массива
echo $ A [ "Ivanov" ][ "name" ]. "<br>" ; // Выводит Иванов И.И.
echo $ A [ "Sidorov" ][ "age" ]. "<br>" ; // Выводит 47
echo $ A [ "Petrov" ][ "email" ]. "<br>" ; // Выводит petrov@mail.ru
?>
Consider some commonly used functions for working with arrays.
List () function
Suppose we have an array consisting of three elements:
$names[0]="Александр";
$names[1]="Николай";
$names[2]="Яков";
Suppose at some point we need to transfer the values of all three elements of the array, respectively, to three variables: $ alex , $ nick , $ yakov . This can be done like this:
$alex = $names[0];
$nick = $names[1];
$yakov = $names[2];
If the array is large, then this method of assigning array elements to variables is not very convenient.
There is a more rational approach - using the list () function:
list ($alex, $nick, $yakov) = $names;
If we need only "Nikolay" and "Yakov", then we can do this:
list (, $nick, $yakov) = $names;
Array () function
The Array () function is used specifically to create arrays. At the same time, it allows you to create empty arrays. Here are the methods for using the Array () function:
<? php
// Создает пустой массив:
$ arr = array ();
// Создает список с тремя элементами. Индексы начинаются с нуля:
$ arr2 = array ( "Иванов" , "Петров" , "Сидоров" );
// Создает ассоциативный массив с тремя элементами:
$ arr3 = array ( "Иванов" => "Иван" , "Петров" => "Петр" , "Сидоров" => "Сидор" );
// Создает многомерный ассоциативный массив:
$ arr4 = array ( "name" => "Иванов" , "age" => "24" , "email" => " ivanov@mail.ru " );
$ arr4 = array ( "name" => "Петров" , "age" => "34" , "email" => " petrov@mail.ru " );
$ arr4 = array ( "name" => "Сидоров" , "age" => "47" , "email" => " sidorov@mail.ru " );
?>
Sorting arrays
Let's start with the simplest - sorting arrays. There are so many functions for this in PHP . With their help, you can sort associative arrays and lists in ascending or descending order, as well as in the order in which you need to - by means of a custom sort function.
Sorting an array by values using the asort () and arsort () functions:
The asort () function sorts an array specified in its parameter, so that its values are in alphabetical (if they are strings) or in ascending (for numbers) order.
At the same time, the links between the keys and the values corresponding to them are preserved, that is, some key pairs => the value simply “pops up” to the top, and some vice versa, “descend”. For example:
$A=array("a"=>"Zero","b"=>"Weapon","c"=>"Alpha","d"=>"Processor");
asort($A);
foreach($A as $k=>$v) echo "$k=>$v ";
// выводит "c=>Alpha d=>Processor b=>Weapon a=>Zero"
// как видим, поменялся только порядок пар ключ=>значение
The arsort () function does the same thing, with one exception: it orders the array not in ascending order, but in descending order.
Sort by key using the ksort () and krsort () functions:
The ksort () function is almost identical to the asort () function, with the difference that the sorting is done not by values, but by keys (in ascending order).
For example:
$A=array("d"=>"Zero", "c"=>"Weapon", "b"=>"Alpha", "a"=>"Processor");
ksort($A);
for(Reset($A); list($k,$v)=each($A);) echo "$k=>$v ";
// выводит "a=>Processor b=>Alpha c=>Weapon d=>Zero"
The function for sorting by keys in reverse order is called krsort () and is used in exactly the same context as ksort () .
Sort by key using the uksort () function:
Quite often we have to sort something by a more complex criterion than just alphabetically. For example, suppose a list of file names and subdirectories in the current directory is stored in $ Files . We may want to display this list not only in lexicographical order, but also so that all directories precede the files. In this case, we should use the uksort () function, having previously written a comparison function with two parameters, as required by uksort () .
<? php
// Эта функция должна сравнивать значения $f1 и $f2 и возвращать:
// -1, если $f1<$f2,
// 0, если $f1==$f2
// 1, если $f1>$f2
// Под < и > понимается следование этих имен в выводимом списке
function FCmp ($ f1 ,$ f2 )
{ // Каталог всегда предшествует файлу
if( is_dir ($ f1 ) && ! is_dir ($ f2 )) return - 1 ;
// Файл всегда идет после каталога
if(! is_dir ($ f1 ) && is_dir ($ f2 )) return 1 ;
// Иначе сравниваем лексикографически
if($ f1 <$ f2 ) return - 1 ; elseif($ f1 >$ f2 ) return 1 ; else return 0 ;
}
// Пусть $Files содержит массив с ключами — именами файлов
// в текущем каталоге. Отсортируем его.
uksort ($ Files , "FCmp" ); // передаем функцию сортировки "по ссылке"
?>
Of course, the connections between keys and values by the function uksort () are preserved, i.e., again, some pairs simply “float” upward, and others “settle”.
Sort by value using the uasort () function
The uasort () function is very similar to uksort () , with the difference that with the replaceable (user-defined) sorting function, it is not the keys that are pushed over but the next values from the array. At the same time, links in key pairs => value are also saved.
Flipping an array with array_reverce ()
The array_reverse () function returns an array, the elements of which are followed in reverse order relative to the array passed in the parameter. At the same time, the connections between keys and values are, of course, not lost. For example, instead of ranking an array in reverse order with arsort () , we can sort it in direct order and then flip it:
$A=array("a"=>"Zero","b"=>"Weapon","c"=>"Alpha","d"=>"Processor");
asort($A);
$A=array_reverse($A);
Of course, the specified sequence lasts longer than the single arsort () call.
Sort the list using the sort () and rsort () functions
These two functions are intended primarily for sorting lists.
The sort () function sorts the list (of course, by value) in ascending order, and rsort () in descending order. An example for the sort () function:
<? php
$ A = array ( "40" , "20" , "10" , "30" );
sort ($ A );
for($ i = 0 ; $ i < count ($ A ); $ i ++) echo "$A[$i]" . "<br>" ;
// выводит 10 20 30 40
?>
Shuffle the list using the shuffle () function
The shuffle () function "shuffles" the list passed to it by the first parameter, so that its values are distributed randomly. Note that, firstly, the array itself changes, and secondly, associative arrays are perceived as lists. Example:
$A=array(10,20,30,40,50);
shuffle($A);
foreach($A as $v) echo "$v ";
The above code snippet displays the numbers 10, 20, 30, 40, and 50 in random order.
Having executed this fragment several times, you may find that the sequence of numbers does not change from start to start. This property is due to the fact that the shuffle () function uses a standard random number generator, which must be initialized before operation.
help call srand () .
Operations with keys and array values
array_flip (array $ arr)
The array_flip () function "runs" through the array and swaps its keys and values. The original $ arr array does not change, and the resulting array is simply returned.
Of course, if there are several elements with the same values in the array, only the last of them will be taken into account:
$A=array("a"=>"aaa", "b"=>"aaa", "c"=>"ccc");
$A=array_flip($A);
// теперь $A===array("aaa"=>"b", "ccc"=>"c");
array_keys (array $ arr [, mixed $ SearchVal])
The array_keys () function returns a list containing all the keys in the $ arr array. If the optional parameter $ SearchVal is specified , then it will return only those keys that correspond to the values of $ SearchVal .
In fact, this function with the specified second parameter is inverse to the operator [] - extracting the value by its key.
array_values (array $ arr)
The array_values () function returns a list of all values in the $ arr associative array. Obviously, such an action is useless for lists, but sometimes justified for hashes.
in_array (mixed $ val, array $ arr)
The in_array () function returns true if an element with a value of $ val is present in the $ arr array.
However, if you often have to do this operation, think: would it not be better to use an associative array and store data in its keys, and not in values? On this you can greatly win in speed.
array_count_values (list $ List)
The array_count_values () function counts the number of times each value occurs in the $ List , and returns an associative array with keys — list items and values — the number of repetitions of these items. In other words, the array_count_values () function counts the frequency of values in the $ List . Example:
$List=array(1, "hello", 1, "world", "hello");
array_count_values($array);
// возвращает array(1=>2, "hello"=>2, "world"=>1)
Merge arrays
Merging (concatenation) of arrays is the operation of creating an array consisting of elements of several other arrays. Merging arrays is a very dangerous operation, since the result of a merge is subject to its own logic, forgetting about which data can be lost. The merging of arrays is implemented using the " + " operator or using the array_merge () function. Merger lists can only be done using the array_merge () function.
Suppose we have two arrays:
$A = array("1"=>"первый", "2"=>"Второй");
$B = array("1"=>"первый", "2"=>"Второй");
Now we merge these two arrays into one $ C array:
$C = $A + $B;
The " + " operator for arrays is not commutative. This means that $ A + $ B is not equal to $ B + $ A.
As a result of the considered example, we get an array of $ C of the following form:
"1"=>"Первый", "2"=>"Второй", "3"=>"Третий", "4"=>"Четвертый"
As a result of $ B + $ A, we get the following array:
"3"=>"Третий", "4"=>"Четвертый", "1"=>"Первый", "2"=>"Второй"
When merging lists, this method does not work. Let us explain this fact by example:
Suppose we have two arrays:
$A = array(10,11,12);
$B = array(13,14,15);
As a result of the merging of the lists $ A and $ B ( $ A + $ B ) we get: 10,11,12. And this is not at all the result that we wanted to get ... This is due to the fact that when you merge lists with the same indices, an element of the first array remains in the resulting array, and in the same place. In this case, we need to use the array_merge () function .
Array_merge () function
The array_merge () function is designed to eliminate all the flaws inherent in the " + " operator for merging arrays. Namely, it merges the arrays listed in its arguments into one large array and returns the result. If the same keys are found in the arrays, the result is a pair of key => value from the array that is located to the right in the argument list. However, this does not affect numeric keys: elements with such keys are placed at the end of the resulting array in any case.
Thus, using array_merge (), we can get rid of all the drawbacks of the " + " operator for arrays. Here is an example that merges two lists into one:
$L1=array(100,200,300);
$L2=array(400,500,600);
$L=array_merge($L1,$L2);
// теперь $L===array(100,200,300,400,500,600);
Always use this function if you need to work with lists, and not with ordinary associative arrays.
Getting part of an array
To get a part of an array, you can use the function array_slice ()
array_slice (array $ Arr, int $ offset [, int $ len])
This function returns a part of an associative array, starting with a pair of key => values with an offset (number) $ offset from the beginning and $ len length (if the last parameter is not specified, to the end of the array).
The $ offset and $ len parameters are set using exactly the same rules as the analogous parameters in the substr () function. Namely, they can be negative (in this case, the reading is carried out from the end of the array), etc. Here are some examples:
$input = array ("a", "b", "c", "d", "e");
$output = array_slice ($input, 2); // "c", "d", "e"
$output = array_slice ($input, 2, -1); // "c", "d"
$output = array_slice ($input, -2, 1); // "d"
$output = array_slice ($input, 0, 3); // "a", "b", "c"
Inserting and deleting array elements
We already know several statements that are responsible for inserting and deleting elements. For example, the operator [] (empty square brackets) adds an element to the end of the array, assigning it a numeric key, and the Unset () operator, along with the extraction by key, deletes the desired element. The PHP language supports many other functions that are sometimes convenient to use.
array_push (alist & $ Arr, mixed $ var1 [, mixed $ var2, ...])
This function adds the elements $ var1 , $ var2 , etc. to the $ Arr list. It assigns numeric indices to them - just as it does for standard [] . If you need to add just one element, it’s probably easier and will use this operator:
array_push($Arr,1000); // вызываем функцию…
$Arr[]=100; // то же самое, но короче
Note that the array_push () function takes an array as a stack, and always adds elements to its end. It returns the new number of elements in the array.
array_pop (list & $ Arr)
The array_pop () function, the opposite of array_push () , removes an element from the top of the stack (that is, takes the last element of the list) and returns it, removing it from $ Arr after that. With this function, we can build constructions that resemble a stack. If the $ Arr list was empty, the function returns an empty string.
array_unshift (list & $ Arr, mixed $ var1 [, mixed $ var2, ...])
The array_unshift function is very similar to array_push () , but adds the listed elements not to the end, but to the beginning of the array. In this case, the order of $ var1 , $ var2, and so on, remains the same, that is, the elements “move” as it were into the list on the left. New list items are, as usual, assigned numeric indices starting at 0 ; however, all the keys of the old elements of the array, which were also numeric, change (most often they increase by the number of inserted values). The function returns the new size of the array. Here is an example of its use:
$A=array(10,"a"=>20,30);
array_unshift($A,"!","?");
// теперь $A===array(0=>"!", 1=>"?", 2=>10, a=>20, 3=>30)
mixed array_shift (list & $ Arr)
The function mixed array_shift retrieves the first element of the $ Arr array and returns it. It strongly resembles array_pop () , but only receives the initial, not the final element, and also produces a fairly strong “shake” of the entire array: after all, when extracting the first element, you have to adjust all the numeric indices of all the remaining elements ...
array_unique (array $ Arr)
The array_unique () function returns an array made up of all the unique values of the $ Arr array, along with their keys. The first key pairs found are placed in the resulting array => value:
$input=array("a" => "green", "red", "b" => "green", "blue", "red");
$result=array_unique($input);
// теперь $result===array("a"=>"green", "red", "blue");
array_splice (array & $ Arr, int $ offset [, int $ len] [, int $ Repl])
The array_splice function, as well as array_slice () , returns the $ Arr subarray, starting with the $ offset index of the maximum length $ len , but at the same time, it does another useful action. Namely, it replaces the elements just specified with what is in the $ Repl array (or simply deletes if $ Repl is not specified). The parameters $ offset and $ len are set in the same way as in the substr () function - namely, they can be negative, in this case the counting starts from the end of the array. Here are some examples:
<? php
$ input = array ( "red" , "green" , "blue" , "yellow" );
array_splice ($ input , 2 );
// Теперь $input===array("red", "green")
array_splice ($ input , 1 ,- 1 );
// Теперь $input===array("red", "yellow")
array_splice ($ input , - 1 , 1 , array ( "black" , "maroon" ));
// Теперь $input===array("red", "green", "blue", "black", "maroon")
array_splice ($ input , 1 , count ($ input ), "orange" );
// Теперь $input===array("red", "orange")
?>
The last example shows that as the $ Repl parameter we can specify a regular, string value, and not an array of one element.
Variables and arrays
compact (mixed $ vn1 [, mixed $ vn2, ...])
The compact () function packages the variables from the current context (global or function context) specified by their names into $ vn1 , $ vn2 , etc. into the array. In this case, pairs with keys equal to the contents of $ vnN and the values of the corresponding variables are formed in the array . Here is an example of using this feature:
$a="Test string";
$b="Some text";
$A=compact("a","b");
// теперь $A===array("a"=>"Test string", "b"=>"Some text")
Why, then, are the function parameters designated as mixed ? The fact is that they can be not only strings, but also lists of strings. In this case, the function sequentially iterates through all the elements of this list, and packages those variables from the current context, the names of which it has encountered. Moreover, these lists may, in turn, also contain lists of strings, etc. True, the latter is used relatively rarely, but here’s an example:
$a="Test";
$b="Text";
$c="CCC";
$d="DDD";
$Lst=array("b",array("c","d"));
$A=compact("a",$Lst);
// теперь $A===array("a"=>"Test", "b"=>"Text", "c"=>"CCC", "d"=>"DDD")
extract (array $ Arr [, int $ type] [, string $ prefix])
The extract () function does the exact opposite of compact () . Namely, it receives the $ Arr array in parameters and turns each key pair => value into a variable of the current context.
Creating a list - a range of numbers
range (int $ low, int $ high)
This feature is very simple. It creates a list filled with integers from $ low to $ high inclusive.
Array count
The count () function is used to count the array elements.
An example of using the count () function:
<? php
$ arr []= 5 ;
$ arr []= 4 ;
$ arr []= 8 ;
$ arr []= 3 ;
$ arr []= 8 ;
echo "<h2>Число элементов массива: " . count ($ arr ). "</h2>" ;
// Выводит: Число элементов массива: 5
?>
Deleting an array and its elements
If you want to delete the entire array, use the unset () function.
If you want to delete a key / value pair, you can also use the unset () function. We give specific examples:
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // В этом месте скрипта это
// эквивалентно $arr[13] = 56;
$arr["x"] = 42; // Это добавляет к массиву новый
// элемент с ключом "x"
unset($arr[5]); // Это удаляет элемент из массива
unset($arr); // Это удаляет массив полностью
?>
one 2 3 four five 6 7 eight 9 ten eleven 12 13 14 15 | $A = array ( 'John' , 'Mary' , 'David' , 'Jack' , 'Jason' ); $B = array ( 'Dexter' , 'William' , 'Jack' , 'John' , 'Christine' ); $C = array_intersect ( $A , $B ); $D = array_diff ( $B , $C ); $E = array_diff ( $A , $C ); //display the results echo 'New list A: ' , print_r( $A , true); echo 'User table B: ' , print_r( $B , true); echo 'Users in user table and new list(Item 1) – do nothing C: ' , print_r( $C , true); echo 'Users in the user table but not in the new list(Item 2) – delete from user table D: ' , print_r( $D , true); echo 'Users in the new list but not in the user table(Item 3) – add to user table E: ' , print_r( $E , true); |
For any of the types: integer , float , string , boolean, and resource , if you convert the value into an array, you get an array with one element (with index 0), which is the scalar value that you started with.
If you convert an object ( object ) into an array, you will receive the properties (member variables) of this object as array elements. The keys are the names of the member variables.
If you convert a null value to an array, you get an empty array.
Arrays can be compared using the array_diff () function and array operators:
Array Operators :
Example | Title | Result |
---|---|---|
$ a + $ b | Union | Combining array $ a and array $ b. |
$ a == $ b | Equally | TRUE if $ a and $ b contain the same elements. |
$ a === $ b | Identically equal | TRUE if $ a and $ b contain the same elements in the same order. |
$ a! = $ b | Not equal | TRUE if array $ a is not equal to array $ b. |
$ a <> $ b | Not equal | TRUE if array $ a is not equal to array $ b. |
$ a! == $ b | Identically not equal | TRUE if the array $ a is not equal identically to the array $ b. |
Array comparison example:
<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
<?php
// это
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // ключом будет 0
);
// полностью соответствует
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // ключом будет 0
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// создаст массив array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// или просто array('a', 'b', 'c')
?>
Another practical example:
<?php
// Массив как карта (свойств)
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
// исключительно числовые ключи
$array = array( 7,
8,
0,
156,
-10
);
// это то же самое, что и array(0 => 7, 1 => 8, ...)
$switching = array( 10, // ключ = 0
5 => 6,
3 => 7,
'a' => 4,
11, // ключ = 6 (максимальным числовым индексом был 5)
'8' => 2, // ключ = 8 (число!)
'02' => 77, // ключ = '02'
0 => 12 // значение 10 будет перезаписано на 12
);
// пустой массив
$empty = array();
?>
Collection:
<?php
$colors = array('красный', 'синий', 'зеленый', 'желтый');
foreach ($colors as $color) {
echo "Вам нравится $color?\n";
}
?>
The result of the considered script:
Do you like red? Do you like blue? Do you like green? Do you like yellow?
The following example creates an array starting at one:
<?php
$firstquarter = array(1 => 'Январь', 'Февраль', 'Март');
print_r($firstquarter);
?>
The result of the script will be as follows:
Array ( [1] => 'January' [2] => 'February' [3] => 'March' ) |
An example of filling the array:
<?php
// заполняет массив всеми элементами директории
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
Arrays are ordered. You can change the order of elements using various sorting functions. See the section on array functions for more information. You can count the number of elements in an array using the count () function.
Recursive and multidimensional arrays:
<?php
$fruits = array ( "фрукты" => array ( "a" => "апельсин",
"b" => "банан",
"c" => "яблоко"
),
"числа" => array ( 1,
2,
3,
4,
5,
6
),
"дырки" => array ( "первая",
5 => "вторая",
"третья"
)
);
// Несколько примеров доступа к значениям предыдущего массива
echo $fruits["дырки"][5]; // напечатает "вторая"
echo $fruits["фрукты"]["a"]; // напечатает "апельсин"
unset($fruits["дырки"][0]); // удалит "первая"
// Создаст новый многомерный массив
$juices["яблоко"]["зеленое"] = "хорошее";
?>
Note that when assigning an array, the value is always copied. To copy an array by reference, you need to use the reference operator:
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 изменился,
// $arr1 по прежнему array(2,3)
$arr3 = &$arr1;
$arr3[] = 4; // теперь $arr1 и $arr3 эквивалентны
?>
We reviewed the main features of working with arrays. You can find some additional information in the "Working with Data" section of PHP articles.
Comments
To leave a comment
Running server side scripts using PHP as an example (LAMP)
Terms: Running server side scripts using PHP as an example (LAMP)