Getting started with arrays in php

Source: Internet
Author: User
Tags arrays numeric prev scalar shuffle sorts

Number index array;
Non-numeric index array;
Array operator;
Two-dimensional array and multi-dimensional array;
Array sorting;
Multi-dimensional array sorting;
Sorts the array;
Execute other array operations;
Number index array
Like the array in C #, you can use the index value of the array to access each item in the array. The default value starts from 0.

Create an array:
Create an array:

1 $ phones = array ('HTC ', 'Moto', 'Nokia ');
Or: 1 $ phones [0] = 'HTC ';

2 $ phones [1] = 'Moto ';

3 $ phones [2] = 'Nokia ';
If $ phones does not exist and $ phones [0] = 'HTC 'is used to create an array with only one element, A new value will be added to this array. The array size changes dynamically.
Access the first and second elements:

1 echo $ phones [0]. '--'. $ phones [1];

If you want to save the numbers in ascending order in the array, you can use the range () function, as shown below: create an array from 1 to 10

1 $ number = range (1, 10 );

This function also has an optional third parameter, which allows you to set the stride between values. For example, you can create an odd number from 1 to 10,

1 $ number = range (1, 10, 2 );

The range () function can also operate on characters. For example, if you need a list of characters from a to z, you can perform the following operations:

1 $ number = range ('A', 'z ');

Access array:
1. for loop

1 $ phones = array ('HTC ', 'Moto', 'Nokia ');

2 for ($ I = 0; $ I <3; $ I ++ ){

3 echo "$ phones [$ I] <br/> ";

4}

2. foreach (specially designed for arrays)

1 $ phones = array ('HTC ', 'Moto', 'Nokia ');

2 foreach ($ phones as $ v ){

3 echo "$ v <br/> ";

4}
Non-numeric index array (related array)
In the $ phones array, PHP is allowed to specify a default index. This means that the index of the first element to be added is 0, and the second element is 1. PHP also supports related arrays (non-numeric index arrays). The values of each variable can be associated with any keyword or index. Similar to Dictionary <TKey, TValue> in C.

Create an array:
1 $ phones = array ('htcg6' => 2400, 'ii9' => 2500, 'nokian8' => 2890 );

The keyword is enclosed in single quotes, and the value is followed by =>.

Access array:
Because the index in the relevant array is not a number, you cannot use the for statement for operations, but you can use the foreach loop or list () and each () structures.

1. foreach access

1 foreach ($ phones as $ key => $ value ){

2 echo "$ key: $ value <br/> ";

3}

2. each access

1 while ($ element = each ($ phones )){

2 echo $ element ['key']; // $ element [0]

3 echo ':';

4 echo $ element ['value']; // $ element [1]

5 echo '<br/> ';

6}

The each () function returns the current element of the array and uses the next element as the current element. In the while loop, it is output in order. $ Element is also an array. When an entry uses each (), the position key or 0 is used to contain the keyword of the current element, and the position value or 1 contains the value of the current element.

3. list access

1 while (list ($ name, $ price) = each ($ phones )){

2 echo $ name;

3 echo ':';

4 echo $ price;

5 echo '<br/> ';

6}

The use of the $ element variable in the list () function is similar to that in method 2. However, the list function can re-specify the custom variable and point to the array with the keywords and values of a group of elements. This is more convenient and clear than method 2.
Array operators
Operations between arrays:


Two-dimensional array and multi-dimensional array
Two-dimensional arrays, as well as the establishment and loop of multi-dimensional arrays and one-dimensional arrays are similar, but an array is added on the basis of one-dimensional arrays.

1 $ phones = array ('xiaomi', 'Xiaomi phone', 1900 ),

2 array ('HTC ', 'g6', 2400 ),

3 array ('Nokia ', 'n8', 3200 ));

This array contains three arrays, each consisting of products, product descriptions, and product prices.

You can use the following method to access this array.

Method 1: directly use a digital index
1 echo '| '. $ phones [0] [0]. '| '. $ phones [0] [1]. '| '. $ phones [0] [2]. '<br/> ';

2 echo '| '. $ phones [1] [0]. '| '. $ phones [1] [1]. '| '. $ phones [1] [2]. '<br/> ';

3 echo '| '. $ phones [2] [0]. '| '. $ phones [2] [1]. '| '. $ phones [2] [2]. '<br/> ';

Method 2: use a dual for loop
1 for ($ row = 0; $ row <3; $ row ++ ){

2 for ($ col = 0; $ col <3; $ col ++ ){

3 echo '|'. $ phones [$ row] [$ col];

4}

5 echo '<br/> ';

6}

The result is the same as that output by Method 1.

Sometimes we may use related arrays to save the data, which looks intuitive, such:
1 $ phones = array ('name' => 'xiaomi', 'desc' => 'Xiaomi phone', 'price' => 1900 ),

2 array ('name' => 'HTC ', 'desc' => 'g6', 'price' => 2400 ),

3 array ('name' => 'Nokia ', 'desc' => 'n8', 'price' => 3200 ));

To traverse the data, you can use the following method.

Method 1
1 for ($ row = 0; $ row <3; $ row ++ ){

2 echo '| '. $ phones [$ row] ['name']. '| '. $ phones [$ row] ['desc']. '| '. $ phones [$ row] ['price']. '<br/> ';

3}

Method 2
Use for to traverse the data on the outermost layer, and then use the method of traversing one-dimensional related arrays.

1 for ($ row = 0; $ row <3; $ row ++ ){

2 while (list ($ key, $ value) = each ($ phones [$ row]) {

3 echo "| $ value ";

4}

5 echo '<br/> ';

6}

Method 1 and method 2 have the same results.

  

The 3D array or 3D array has been mounted, similar to the 2D array method, that is, the nested array on the 2D array. Traversal is also based on two-dimensional traversal and nested at a layer. I will talk about it here.
Array sorting
The following sorting only applies to one-dimensional array sorting.

1, sort () function
The following code sorts data by character

1 $ products = array ('HTC ', 'Nokia', 'Moto ');

2 foreach ($ products as $ value ){

3 echo "$ value <br/> ";

4}

5 sort ($ products );

6 echo '------------ <br/> ';

7 foreach ($ products as $ value ){

8 echo "$ value <br/> ";

9}

You can also sort data in ascending order of numbers.

1 $ products = array (2,100, 5 );

2 foreach ($ products as $ value ){

3 echo "$ value <br/> ";

4}

5 sort ($ products );

6 echo '------------ <br/> ';

7 foreach ($ products as $ value ){

8 echo "$ value <br/> ";

9}

Output 100

The second parameter of the function is optional. You can pass SORT_GEGULAR (default), SORT_NUMERIC or SORT_STRINT. It is very useful to specify the sorting type. For example, when

For strings that may contain numbers 2 and 12, '12' is indeed less than '2'

Note: The time zone of the sort () function is case sensitive.

2. asort () and ksort () functions
If the Key or Value in the related array are consistent during sorting, you need to use these two functions.

Ksort function: Sort keys in related arrays in ascending order.

1 $ phones = array ('htcg6' => 2400, 'nokian8' => 2890, 'ii9' => 3200 );

2 ksort ($ phones );

Output: htcG6, motoI9, nokiaN8

Asort function: sort values in related arrays in ascending order.

1 $ phones = array ('htcg6' => 2400, 'nokian8' => 2890, 'ii9' => 3200 );

2 asort ($ phones );

Output: 3200

3. Reverse sorting
All of the above are sorted in ascending order. If descending order is required, use the descending function corresponding to each function.

Sort () => rsort ()

Ksort () ==> krsort ()

Asort () => arsort ()

The usage is the same.
Multi-dimensional array sorting
In multi-dimensional arrays, arrays contain arrays, which are sorted by certain conditions. Therefore, sorting is much more complex than sorting one-dimensional arrays.

1. User-defined sorting
1 $ phones = array ('name' => 'xiaomi', 'desc' => 'Xiaomi phone', 'price' => 1900 ),

2 array ('name' => 'HTC ', 'desc' => 'g6', 'price' => 1400 ),

3 array ('name' => 'Nokia ', 'desc' => 'n8', 'price' => 3200 ));

It is troublesome to sort the preceding two-dimensional data. Because there are three conditions and different conditions, the sorting algorithm may be different, so you need to customize the sorting algorithm.

The usort () function provides two parameters. The first parameter is the object to be sorted, and the second parameter is the custom function. As follows:

1 $ phones = array ('name' => 'xiaomi', 'desc' => 'Xiaomi phone', 'price' => 1900 ),

2 array ('name' => 'HTC ', 'desc' => 'g6', 'price' => 1400 ),

3 array ('name' => 'Nokia ', 'desc' => 'n8', 'price' => 3200 ));

4 function compare ($ x, $ y ){
1 if ($ x ['price'] = $ y ['price']) {

2 return 0;

3} else if ($ x ['price'] <$ y ['price']) {
1 return-1;

2} else {

3 return 1;

4}

5}
Usort ($ phones, 'Company'); 1

2 for ($ row = 0; $ row <3; $ row ++ ){

3 while (list ($ key, $ value) = each ($ phones [$ row]) {

4 echo "| $ value ";

5}

6 echo '<br/> ';

7}

The compare () function above accepts two arrays to be compared. Output in ascending order of price.

To sort names, replace the price in the compare () function with the name.

"U" in usort () indicates "user", because this function requires passing in user-defined functions. The uasort and uksort versions corresponding to asort and ksort also require the input of user-defined functions.

Similar to asort and ksort, uasort and uksort are used only when related arrays are sorted.

2. Reverse user sorting
The sort (), asort (), and ksort () functions correspond to a reverse sorting function with the letter "r" respectively. User-defined sorting does not have reverse bodies. However, you only need to reverse the return value of the user-defined function. For example:

1 function compare ($ x, $ y ){

2 if ($ x ['price'] = $ y ['price']) {

3 return 0;

4} else if ($ x ['price']> $ y ['price']
1 ){

2 return-1;

3} else {

4 return 1;

5}

6}
Sorts arrays again
1. Use the shuffle () function
We may need to randomly display three of the 10 ads, so this function will be useful. As follows:

1 $ myChars = range ('A', 'z ');

2 shuffle ($ myChars );

3 for ($ I = 0; $ I <3; $ I ++ ){

4 echo $ myChars [$ I]. '<br/> ';

5}

The above code selects three random characters from the a-z26.

You can also use the array_rand () function, but this function returns an array. As follows:

1 $ myChars = range (1, 10 );

2 $ rChars = array_rand ($ myChars, 2); // The first parameter is an array object, and the second parameter is optional. The default value is 1. Number of random elements returned.

3 echo $ rChars [0]. '-'. $ rChars [1];

2. Use the array_reverse () function. If we want to flip an array, this function will be useful. For example, we want to output,. Although the for loop works, three lines of code are required.

The array_reverse () function uses the following:

1 $ numbers = range (1, 10 );

2 $ numbers = array_reverse ($ numbers );

3 foreach ($ numbers as $ value ){

4 echo $ value. '<br/> ';

5}
Execute other array operations
1. Browsing in the array: each (), current (), reset (), end (), next (), pos () and prev ()
Each () indirectly uses the array pointer, and other functions directly use this pointer.

If you create a new array, the current pointer is initialized and points to the first element. When you call current ($ array_name), the first element is returned.

Calling each () and next () will move the pointer forward. Calling each ($ array_name) will return the current element before the pointer moves forward. The next () function does not need to be used. It moves the pointer forward and then returns the new current element.

The reset () function returns a pointer to the first element of the array (sometimes the pointer is moved to a certain position in the array. We want to reset the array and use this function ). Call end ($ array_name) to move the pointer to the end of the data. Reset () and end () will return the first and last elements of the array.

The prev () function is the opposite of next.

2. Apply any function to each element of the array: array_walk ()
Sometimes, each element of the array is used or modified in the same way. Then array_walk provides such operations.

The array_walk () function is prototype as follows:

1 bool array_walk (array arr, string func, [mixed userdata]);

The first parameter is arr, which is the array to be processed.

The second parameter is a user-defined function. To process every element in the array, you need to write custom operations.

The third parameter is optional. If it is used, it can be passed to our custom function as a parameter.

1 $ numbers = range (1, 10 );

2 function show_even_number ($ value ){

3 if ($ value % 2 = 0 ){

4 echo $ value. '<br/> ';

5}

6}

7 array_walk ($ numbers, 'show _ even_number ');

The code above only shows an even number.

We can also modify each element in the array and so on. As follows:

1 $ numbers = range (1, 10 );

2 function replace_number (& $ value, $ key, $ userdata ){

3 $ value = $ value * $ userdata;

4}

5 array_walk ($ numbers, 'replace _ number', 2 );

6 foreach ($ numbers as $ value ){

7 echo $ value. '<br/> ';

8}

The above code uses the third parameter of the array_walk () function, multiplication factor, which can be changed at any time according to the business logic without being fixed in the custom function. Note that an & symbol is added before the $ value variable, indicating that the reference of the variable is passed, similar to the ref or out in C.

3. count the number of array elements: count (), sizeof (), and array_count_values ()
Both the count () and sizeof () functions can calculate the number of elements in the array element. If the array is an empty array or an uninitialized variable, 0 is returned;

1 $ numbers = range (1, 10 );

2 echo count ($ numbers); // sizeof ($ numbers)

The array_count_values () function returns an array of the number of occurrences of each element in the array. As follows:

1 $ numbers = array (5, 1, 8, 5, 3, 0, 4, 3, 5 );

2 $ ac = array_count_values ($ numbers );

3 while (list ($ key, $ value) = each ($ ac )){

4 echo $ key. '--'. $ value. '<br/> ';

5}

The output is as follows:

5-3

2 1--1

3 8-1

4-2

5 0--1

6 4--1

4. Convert the array into a scalar variable: extract ()
The extract () function is used to convert an array into a series of scalar variables. The names of these variables must be keys in the array, while the values of these variables must be values in the array. As follows:

1 $ phones = array ('name' => 'xiaomi', 'price' => 1999, 'OS' => 'Android ');

2 extract ($ phones );

3 echo "$ name = >$ price => $ OS ";

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.