Php array usage tips and Operations summary, php array usage tips

Source: Internet
Author: User
Tags array definition

Php array usage tips and Operations summary, php array usage tips

Array is an important method in PHP Data Applications. PHP has a large number of array functions. The following is a summary to help you easily identify them later.

1. array Definition
The array definition uses the array () method to define an empty array:
<? Php
$ Number = array (1, 3, 5, 7, 9 );
// Define an empty array
$ Result = array ();
$ Color = array ("red", "blue", "green ");
// Custom key value
$ Language = (1 => "English", 3 => "Chinese", 5 => "Franch ");
// Define a two-dimensional array
$ Two = array (
"Color" => array ("red", "blue"), // end with a comma
"Week" => array ("Monday", "Friday") // The last sentence contains no punctuation.
);
?>

2. Create an array
Compact ()
Compact () function-converts one or more variables (including arrays) to an array: array compact (mixed $ varname [, mixed $...]).
<? PHP
$ Number = "1, 3, 5, 7, 9 ";
$ String = "I'm PHPer ";
$ Array = array ("And", "You? ");
$ NewArray = compact ("number", "string", "array ");
Print_r ($ newArray );
?>
The compact () function is used to convert two or more variables to an array. Of course, it also contains array variables. The parameter is the variable name, not the $ full name. The opposite function is extract (). As the name suggests, it is to convert an array into a single string. The key value is used as the string name, And the array value is used as the string value.
Running result:

Array (
[Number] => 1, 3, 5, 7, 9
[String] => I'm PHPer
[Array] => Array ([0] => And [1] => You? )
)
Array_combine ()
Array_combine () -- combines two arrays into an array, one as the key value and the other as the value: array array_combine (array $ keys, array $ values)
<? PHP
$ Number = array ("1", "3", "5", "7", "9 ");
$ Array = array ("I", "Am", "A", "PHP", "er ");
$ NewArray = array_combine ($ number, $ array );
Print_r ($ newArray );
?>
The array_combine function is not much to talk about. Everyone can understand it.
Running result:
Array ([1] => I [3] => Am [5] => A [7] => PHP [9] => er)
Range ()
Range () function -- create an array of the specified range:
<? PHP
$ Array1 = range (0,100, 10); // 0 indicates the start value, 100 indicates the end value, and 10 indicates the step value (the default step value is 1 ).
Print_r ($ array1 );
Echo "<br/> ";
$ Array2 = range ("A", "Z ");
Print_r ($ array2 );
Echo "<br/> ";
$ Array3 = range ("z", "");
Print_r ($ array3 );
?>
Array_fill ()
Array_fill () function -- fill Array Function:
<? PHP
$ Array = range (1, 10 );
$ Fillarray = range ("a", "d ");
$ ArrayFilled = array_fill (, $ fillarray); // $ fillarray can be a string, such as "test ".
Echo "<pre> ";
Print_r ($ arrayFilled );
Echo "</pre> ";
$ Keys = array ("string", "2", 9, "SDK", "PK ");
$ Array2 = array_fill_keys ($ keys, "testing ");
Echo "<pre> ";
Print_r ($ array2 );
Echo "</pre> ";
?>
Running result:
Array
(
[0] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)

[1] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)

[2] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)

[3] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)

[4] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)

)
Array
(
[String] => testing
[2] => testing
[9] => testing
[SDK] => testing
[PK] => testing
)

3. array Traversal
Foreach Traversal
Foreach (array_expression as $ value ){}
Foreach (array_expression as $ key => $ value ){}

<? PHP
$ Speed = array (50,120,180,240,380 );
Foreach ($ speed as $ keys => $ values ){
Echo $ keys. "=>". $ values. "<br/> ";
}
?>
Running result:
0 => 50
1 => 120
2 => 180
3 => 240
4 => 380
While loop Traversal
While loop traversal is generally combined with the list function, the following is an instance
<? PHP
$ Staff = array (
Array ("name", "gender", "Age "),
Array ("Xiao Zhang", "male", 24 ),
Array ("Wang", "female", 25 ),
Array ("Xiao Li", "male", 23)
);
Echo "<table border = 2> ";
While (list ($ keys, $ value) = each ($ staff )){
List ($ name, $ sex, $ age) = $ value;
Echo "<tr> <td> $ name </td> <td> $ sex </td> <td> $ age </td> </tr> ";
}
Echo "</table> ";
?>
For Loop Traversal
<? PHP
$ Speed = range (0,220, 20 );
For ($ I = 0; $ I <count ($ speed); $ I ++ ){
Echo $ speed [$ I]. "";
}
?>
Running result:
0 20 40 60 80 100 120 140 160 180 200
4. array pointer operation
Involved functions include reset, prev, end, next, current, and each.
Example 1: next and prev
<? PHP
$ Speed = range (0,220, 20 );
Echo current ($ speed); // output the value of the current position (at the beginning of the array)
$ I = rand (1, 11 );
While ($ I --){
Next ($ speed); // the pointer moves one digit backward from the current position
}
Echo current ($ speed); // output the value of the current position
Echo "<br/> ";
Echo prev ($ speed); // output the array value in the previous position
Echo "<br/> ";
Echo reset ($ speed); // reset the pointer to the starting position.
Echo "<br/> ";
Echo end ($ speed); // output the array value at the last position
Echo "<br/> ";
?>
Running result:
0220
200
0
220
Example 2: each function pointer operation
<? PHP
$ Speed = range (0,200, 40 );
Echo "each implement pointer down <br/> ";
Echo "the speed of 0 blocks is". current (each ($ speed). "<br/> ";
Echo "1 speed is". current (each ($ speed). "<br/> ";
Echo "the speed of 2 blocks is". current (each ($ speed). "<br/> ";
Echo "the speed of 3 blocks is". current (each ($ speed). "<br/> ";
Echo "the speed of 4 blocks is". current (each ($ speed). "<br/> ";
Echo "the speed of 5 blocks is". current (each ($ speed). "<br/> ";
Echo "Use the each function to move the array pointer and traverse the array <br/> ";
Reset ($ speed); // The array Pointer Points to the first part of the array.
While (list ($ key, $ value) = each ($ speed )){
Echo $ key. "=>". $ value. "<br/> ";
}
?>
Running result:
Each implements pointer moving down
The speed of 0 blocks is 0.
The speed of Block 1 is 40.
The speed of two blocks is 80.
The speed of 3 blocks is 120.
The speed of 4 blocks is 160.
The speed of the fifth gear is 200.
Use the each function to move the array pointer and traverse the array.
0 => 0
1 => 40
2 => 80
3 => 120
4 => 160
5 => 200.
5. array addition and deletion operations

Add an array Member
Example 1: $ num [] = value is directly assigned to the end of the array:
[Code] <? PHP
$ Num = array (1 => 160 =>, 3 => );
Echo "using expressions to add array members <br/> ";
$ Num [] = 240;
Print_r ($ num );
?>

Running result:
Add array members using expressions
Array ([0] => 80 [1] => 120 [2] => 160 [3] => 240)
Example 2: array_pad function, which selectively appends the first and end of an array

<? PHP
$ Num = array (1 => 160 =>, 3 => );
$ Num = array_pad ($ num, 4,200 );
Echo "Use the array_pad function to add members to the end of the array <br/> ";
Print_r ($ num );
Echo "<br/> array_pad can also fill the array header <br/> ";
$ Num = array_pad ($ num,-8, 40 );
Print_r ($ num );
?>

Running result:
Use the array_pad function to add members to the end of the array.
Array ([0] => 80 [1] => 120 [2] => 160 [3] => 200)
Array_pad can also fill the array Header
Array ([0] => 40 [1] => 40 [2] => 40 [3] => 40 [4] => 80 [5] => 120 [6] => 160 [7] => 200)
Example 3: append an inbound stack (array_push ):
<? PHP
$ Num = array (1 => 160 =>, 3 => );
Array_push ($ num, 200,240,280); // You can append it by yourself and add it directly to the end of the array.
Print_r ($ num );
?>

Running result:
Array ([1] => 80 [2] => 120 [3] => 160 [4] => 200 [5] => 240 [6] => 280)
Example 4: add an array member at the beginning of array_unshift ()

<? PHP
$ Num = array (1 => 160 =>, 3 => );
Array_unshift ($ num,); // You can append the value by yourself and add it directly to the end of the array.
Print_r ($ num );
?>

Running result:
Array ([0] => 0 [1] => 40 [2] => 80 [3] => 120 [4] => 160)
Note: After the array_unshift () function is used, the key value of the array starts from 0!
Delete an array Member
Example 1: unset () command to delete an array member or array:
Copy the Code as follows: <? PHP
$ Num = array_fill (0, 5, rand (1, 10 ));
Print_r ($ num );
Echo "<br/> ";
Unset ($ num [4]);
Print_r ($ num );
Echo "<br/> ";
Unset ($ num );
If (is_array ){
Echo "the unset command cannot delete the entire array ";
} Else {
Echo "the unset command can delete arrays ";
}
?>

Running result: (the running error and description array are also deleted and no longer exist)
Array ([0] => 9 [1] => 9 [2] => 9 [3] => 9 [4] => 9)
Array ([0] => 9 [1] => 9 [2] => 9 [3] => 9)

Notice: Use of undefined constant is_array-assumed 'is _ array' in H: \ wamp \ www \ testing \ editorplus \ test. php on line 21
The unset command cannot delete the entire array.
Example 2: The array_splice () function deletes an array member.
<? Php
$ A = array ("red", "green", "blue", "yellow ");
Count ($ a); // get 4
Array_splice ($ a,); // deletes the second element.
Count ($ a); // get 3
Echo $ a [2]; // obtain yellow
Echo $ a [1]; // get blue
?>

Example 3: array_unique:

<? Php
$ A = array ("red", "green", "blue", "yellow", "blue", "green ");
$ Result = array_unique ($ );
Print_r ($ result );
?>
Running result:
Array ([0] => red [1] => green [2] => blue [3] => yellow)
Example 4: array_merge and array_merge_recursive merge Arrays
<? Php
$ Array1 = array ("r" => "red", 1, 2, 3, 4 );
$ Array2 = array ("B" => "blue", 4 => 5, 6, 7, 8, 9 );
$ Array3 = array ("r" => "read", 4 => 10, 2 => 11 );
$ Array4 = array (
Array (4 => 10 ),
Array (7 => 13)
);
$ Array5 = array (
Array (4 => 11 ),
Array (6 => 12)
);
$ Result = array_merge ($ array1, $ array2, $ array3, $ array4, $ array5 );
Echo "<pre> ";
Print_r ($ result );
Echo "</pre> ";
$ Result = array_merge_recursive ($ array1, $ array2, $ array3, $ array4, $ array5 );
Echo "<pre> ";
Print_r ($ result );
Echo "</pre> ";
?>
Array
(
[R] => read
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[B] => blue
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => Array
(
[4] => 10
)

[12] => Array
(
[7] => 13
)

[13] => Array
(
[4] => 11
)

[14] => Array
(
[6] => 12
)

)
Array
(
[R] => Array
(
[0] => red
[1] => read
)

[0] => 1
[1] => 2
[2] => 3
[3] => 4
[B] => blue
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => Array
(
[4] => 10
)

[12] => Array
(
[7] => 13
)

[13] => Array
(
[4] => 11
)

[14] => Array
(
[6] => 12
)

)
Note: 1. If the key name of array_merge is a number, the index will be re-created. If the same string key name is used, the subsequent key name will overwrite the previous one. 2. The array_merge_recursive function integrates the key list elements of the same string into an array.
6. array key value and value operations
Example 1: in_array () checks whether a value exists in the array.

<? Php
$ Array = range (0, 9 );
If (in_array (9, $ array )){
Echo "exists in the array ";
}
?>
Running result: An array exists.


Example 2: key () gets the current key name of the array:

<? Php
$ Array = range (0, 9 );
$ Num = rand (0, 8 );
While ($ num --)
Next ($ array );
$ Key = key ($ array );
Echo $ key;
?>
The result of this instance is a dynamic result in the range of (0-8) and is not displayed.


Example 3: The list () function assigns the values in the array to the specified variable:
Array ("Xiao Li", "male", 23)
);
Echo "<table border = 2> ";
While (list ($ keys, $ value) = each ($ staff )){
List ($ name, $ sex, $ age) = $ value;
Echo "<tr> <td> $ name </td> <td> $ sex </td> <td> $ age </td> </tr> ";
}
Echo "</table> ";
?>


Example 4: array_flip () swap the key value and value of the array:

<? PHP
$ Array = array ("red", "blue", "yellow", "Black ");
Print_r ($ array );
Echo "<br/> ";
$ Array = array_flip ($ array );
Print_r ($ array );
?>

Running result:
Array ([0] => red [1] => blue [2] => yellow [3] => Black)
Array ([red] => 0 [blue] => 1 [yellow] => 2 [Black] => 3)

<? PHP
$ Array = array ("red", "blue", "yellow", "Black ");
$ Result = array_keys ($ array );
Print_r ($ result );
Echo "<br/> ";
$ Result = array_values ($ array );
Print_r ($ result );
?>

Running result:
Array ([0] => 0 [1] => 1 [2] => 2 [3] => 3)
Array ([0] => red [1] => blue [2] => yellow [3] => Black)
Example 6: array_search () Search value:

<? PHP
$ Array = array ("red", "blue", "yellow", "Black ");
$ Result = array_search ("red", $ array );
If ($ result = NULL )){
Echo "no value red ";
} Else {
Echo "value $ result ";
}
?>

Result: A value of 0 exists.
The value returned by the array_search () function may be false, 0, or NULL. Therefore, be sure to use "=" when determining the value"
7. Sort Arrays
Example 1: Sorting arrays by sort (), rsort ()/asort (), and arsort:

<? PHP
$ Array = array ("B", "c", "d", "");
Sort ($ array); // sort from low to high
Print_r ($ array );
Echo "<br/> ";
Rsort ($ array); // reverse sorting
Print_r ($ array );
?>

Result:
Array ([0] => a [1] => B [2] => c [3] => d)
Array ([0] => d [1] => c [2] => B [3] =>)
The sort () and rsort () functions sort arrays in ascending order and return bool values;
The asort () and arsort () functions retain the sorting of key values. After sorting, the key values are not re-indexed.
Example 2: disrupt the array order -- shuffle () function:

<? PHP
$ Array = array ("a", "B", "c", "d ");
Shuffle ($ array); // sort from low to high
Print_r ($ array );
?>

The result is dynamic:
Array ([0] => c [1] => a [2] => d [3] => B)
The shuffle result is a bit random, and each refresh is different.
Example 3: reverse direction of the array_reverse () array:

<? PHP
$ Array = array ("d", "B", "a", "c ");
$ Array = array_reverse ($ array); // sort from low to high
Print_r ($ array );
?>

Running result:
Array ([0] => c [1] => a [2] => B [3] => d)
Example 4: Natural sorting algorithms natsort () and natcasesort ();

<? PHP
$ Array = array ("sort2", "Sort5", "sort1", "sort4 ");
Natsort ($ array); // sort from low to high
Print_r ($ array );
Echo "<br/> ";
Natcasesort ($ array );
Print_r ($ array );
?>

Result:
Array ([1] => Sort5 [2] => sort1 [0] => sort2 [3] => sort4)
Array ([2] => sort1 [0] => sort2 [3] => sort4 [1] => Sort5)
Natsort () and natcasesort () are used to sort arrays in a natural way. Natcasesort ignores case sensitivity.
Example 5: sort the key values of the array ksort ():

<? PHP
$ Array = array (1 => "sort2", 4 => "Sort5", 2 => "sort1", 3 => "sort4 ");
Ksort ($ array); // sort from low to high
Print_r ($ array );
?>

Result:
Array ([1] => sort2 [2] => sort1 [3] => sort4 [4] => Sort5)
Note: The ksort () function re-creates an index.
8. Other array usage

Cout ($ array) -------- count the number of units in the array
Array_diff ($ array1, $ array2) ---------- calculate the differences between arrays, and return the results that are included in the first array but not in the second array.
Array_diff_assoc ($ array1, $ array2) --------- same as array_diff (), but it only compares key values
Array_diff_key ($ array1, $ array2) ---------- compare key values
Array_product ($ array) ----------- returns the product of all numbers in the array.
Array_sum ($ array) ------------ sum of all values
Array_rand ($ array, $ n) ---------- In the $ array, get $ n values and return the array
Array_intersect ($ array1, $ array2) -------------- get the intersection of two Arrays
Array_intersect_assoc ($ array1, $ array2) ------------- perform key value comparison based on array_intersect
Array_intersect_key ($ array1, $ array2) --------------- compare the intersection of the key values of the two Arrays

 

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.