Php array operation learning Notes

Source: Internet
Author: User
Tags arrays sorts

What is an array?

An array is a collection of data, which is equivalent to a container. Data can be stored in this container according to certain rules. This is equivalent to a hotel. There are many rooms in the hotel, and the rooms are numbered according to certain rules.

Array structure: the basic structure is as follows:

$ Array name (key) = value array name: an array is different from another array, just as each hotel has a name.
Key: It is also a pointer, index, or identifier. The key represents the location where a value is stored in the array. It is equivalent to the hotel room number and can be named in different ways. The query key can be used to find the corresponding value.
Value: The value is equivalent to the memory in the room.

Assign values to create an array

In php, there are two methods to create an array: variable assignment and function call. Here we will first talk about the former.

You can assign values to an array variable directly.

Instance:

The code is as follows: Copy code

<? Php
$ Lang [] = "php ";
$ Lang [] = "html ";
$ Lang [] = "css ";
Echo "$ lang [0] <br> ";
Echo "$ lang [1] <br> ";
Echo "$ lang [2] <br> ";
?>

Array content generated by the three assignment statements:

0 => php

1 => html

2 => css

Create an array

In addition to the value assignment to create an array, you can also call the function to create an array.

Php provides an array function to assemble an array. The basic structure is as follows:

Array (item1, item2. .., itemn)

/* Item indicates the element value in the array. When the array () function creates an array, it automatically assigns an identifier to the element value, increasing from 0 */
Instance:

The code is as follows: Copy code

<? Php
$ Student = array ("Tom", "Jacky", "Rose ");
Echo $ student [0]. "t ";
Echo $ student [1]. "t ";
Echo $ student [2];
?>

Array key name

1. Key name allocation

When you use the array () function to create an array, the key name is automatically assigned to each value. In addition, you can assign a key name to the element as needed.

Basic structure:

Array (key => item)

Instance 1:

The code is as follows: Copy code
<? Php
$ A = array (1 => "you", 2 => "are", 5 => "how ");
Echo $ a [5];
Echo $ a [2];
Echo $ a [1];
?>

2. Use a string as the key name

You can use an integer as the key name or a string as the key name. Use a string as an array of key names to become a string Index (string-indexed) array.

Instance 2:

The code is as follows: Copy code
<? Php
$ A = array ("php" => "dynamic webpage", "html" => "static webpage", "css" => "webpage layout ");
Echo $ a ["php"]. "<br> ";
Echo $ a ["html"]. "<br> ";
Echo $ a ["css"];
?>

3. Key name modification

Instance 3:

The code is as follows: Copy code

<? Php
$ Arr = array ("a" => "Sina ",
"B" => "NetEase ",
"C" => "Tencent", "Yahoo"
);
$ Arr [a] = "PHP Chinese community ";
$ Arr ['E'] = "Sina ";
$ Arr [] = "Baidu ";
Echo $ arr ['A']. "<br> ";
Echo $ arr ['B']. "<br> ";
Echo $ arr ['c']. "<br> ";
Echo $ arr ['E']. "<br> ";
Echo $ arr [0]. "<br> ";
Echo $ arr [1]. "<br> ";
?>

Create multi-dimensional array

When writing a php program, a one-dimensional array sometimes cannot meet the requirements, and a multi-dimensional array is required. A multi-dimensional array adds one or more sub-scripts based on a one-dimensional array. Its usage is roughly the same as that of a one-dimensional array, but operations on multi-dimensional data are more complex, but the functions are more powerful.

Take a two-dimensional array as an example. Just like a small house in a big house, the representation is $ a [0] [0].

Instance:

The code is as follows: Copy code

<? Php
$ A [0] [0] = 1;
$ A [0] [1] = 2;
$ A [0] [2] = 3;
$ A [1] [0] = 4;
$ A [1] [1] = 5;
$ A [1] [2] = 6;
For ($ I = 0; $ I <= 1; $ I ++ ){
For ($ j = 0; $ j <= 2; $ j ++ ){
Echo "$ a [$ I] [$ j] = ". $ a [$ I] [$ j]. "<br>";/* "$" indicates the output variable symbol $ */
  }
 }
?>

Output array

An output array is used to display all element data of an array in a browser. How does php output an array? Common php output array functions include var_dump () and print_r.

1. The var_dump function recursively expands array elements to display the types, key names, and element values of each element in the array.

Instance 1:

The code is as follows: Copy code
<? Php
$ A = array (0, 5, array ("php", "html", "css");/* Create a nested array */
Var_dump ($ );
?>

2. The print_r function value displays the key name and element value of the array element.

Instance 2:

The code is as follows: Copy code


<? Php
$ B = array (1, 2, 3 );
Print_r ($ B );
?>

Test array


Sometimes we do not know whether a variable is an array. We can use the is_array () function to test and determine whether a variable is an array.

Basic structure:

Is_array (variable volume)

Checks whether the variable is an array. If yes, true is returned. Otherwise, false is returned.

Instance:

The code is as follows: Copy code

<? Php
$ A = "apple iphone ";
If (is_array ($ )){
Var_dump ($ );
  }
Else echo "not an array ";
?>

Foreach traversal array


When using arrays, we often need to traverse the array and obtain each key or element value. php provides some functions dedicated to traversing the array. This section describes the usage of foreach's array Traversal function.

Structure:

The code is as follows: Copy code


Foreach (array_expression as $ value) statement
/* Array_expression is the array to be traversed
As is used to assign the value of the array to $ value.
Statement is a subsequent statement.
*/
Instance 1:

<? Php
$ Color = array ('White '=> 'white ',
'Black' => 'black ',
'Red' => 'red ',
'Green' => 'green ',
'Yellow' => 'yellow ');
Foreach ($ color as $ c) echo $ c. "<br> ";
?>

Using foreach, you can obtain not only the element value, but also the key name. The structure is as follows:

Foreach (array_expression as $ key => $ value) statement

Run the following code on the above instance:

 

The code is as follows: Copy code

Foreach ($ color as $ c) echo $ c. "<br> ";
Changed:


Foreach ($ color as $ key => $ c) echo $ key. $ c. "<br> ";


Search for array element values

Php can use array_search () to obtain the array key name. The structure is as follows:

Array_search ($ needle, $ haystack)
/* Parameter $ needle indicates the value to be searched */
/* $ Haystack indicates the object to be searched */
The array_search () function returns a key name rather than a Boolean value. If no value is found, false is returned. If the first element is found, 0 is returned. Php will automatically convert to false, so you need to use "=" to determine the return value. ("=" Indicates whether the request is complete. For details, refer to the php relational operator)

Instance:

The code is as follows: Copy code

<? Php
$ S = array ("a", "B", "c", "d", "e", "f ");
$ I = array_search ("a", $ s);/* check whether the array contains the character ""*/
If ($ I = false)/* judge the search result */
Echo "the character 'A' cannot be found in array s '";
Else echo "key name of the output array $ s:". $ I;/* output key name */
?>

Calculate the number of array elements

Arrays can also be computed like Variables. For example, when php needs to count the number of array elements, we can use the count () function to calculate the number of elements in the array.

Structure:

The code is as follows: Copy code


Count ($ var, $ mode)
/* $ Var parameter $ var is usually an array, and the function returns the number of units in var */
/* Mode is an optional parameter */
Instance:

<? Php
$ A = array ("peple", "man", "women ");
$ B = count ($ a);/* count the number of array elements */
Echo $ B;
?>

Array sorting

Php provides a series of array sorting functions. We can sort arrays as needed. There are three main ways to sort arrays:

Sort key values

That is, the sequence is arranged by the size of the ASC Ⅱ value.

Ksort (): Sort by array identifier
Krsort (): Sort by array identifier in reverse order
Instance 1:

The code is as follows: Copy code
<? Php
$ Ages = array (
'C' => 'php ',
'D' => 'asp ',
'A' => 'JSP ',
'B' => 'Java'
);
Krsort ($ ages );
Foreach ($ ages as $ key => $ val ){
Echo "$ key = $ val". '<br> ';
};
?>

Sort by element value

Asort (): sorts arrays in ascending order;
Rsort (): sort the array in descending order.
Change the line 8-11 of instance 1:

 

The code is as follows: Copy code
Asort ($ ages );
Print_r ($ ages );
Echo "<br> ";
Rsort ($ ages );
Print_r ($ ages );

Delete the sorting of original key names

Sort (): sorts arrays in ascending order;
Rsort (): sort the array in descending order.
Change the 8-11 line code of instance 2:

 

The code is as follows: Copy code

Sort ($ ages );
Foreach ($ ages as $ key => $ val ){
Echo "ages [$ key] = $ val". '<br> ';
};

 

Array operators

Merge array computing instances:

The code is as follows: Copy code
<? Php
$ A = array (
'A' => 'php ',
'B' => 'html ',
'C' => 'css'
);
$ B = array (
'A' => 'asp ',
'B' => 'JSP'
);
$ C = $ a + $ B;/* merge arrays */
Var_dump ($ c );
Echo "<br> ";
$ C = $ B + $ a;/* transpose order merge array */
Var_dump ($ c );
?>

Array comparison example:

The code is as follows: Copy code
<? Php
$ A = array ('php', 'asp ');
$ B = array (1 => 'asp ', 0 => 'php ');
Var_dump ($ a = $ B );
Var_dump ($ a ===$ B );
?>

Array operators
Example Name Result
$ A + $ B Union $ A and $ B.
$ A = $ B Equal If $ a and $ B have the same key/value pairTRUE.
$ A ===$ B Full If $ a and $ B have the same key/value pairs and the order and type are the sameTRUE.
$! = $ B Not supported If $ a is not equal to $ BTRUE.
$ A <> $ B Not supported If $ a is not equal to $ BTRUE.
$! ==$ B Incomplete If $ a is not equal to $ BTRUE.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.