PHP Array Operations summary PHP array usage tips

Source: Internet
Author: User
Tags compact shuffle

For Web programming, the most important thing is to access and read and write data. There may be many ways to store them, such as strings, arrays, files, and so on. arrays, which can be said to be a more important way of data application in PHP. PHP array functions are numerous, the following is my study of the summary, take this to remember, easy to learn later.
1. Array definitions
The definition of an array is defined using the array () method, and an empty array can be defined:
Copy CodeThe code is as follows:
<?php
$number = Array (1,3,5,7,9);
Defining an empty array
$result = Array ();
$color =array ("Red", "Blue", "green");
Custom Key values
$language = (1=> "中文版",3=> "Chinese",5=> "Franch");
Defining a two-dimensional array
$two = Array (
"Color" =>array ("Red", "blue"),//end with a comma
"Week" =>array ("Monday", "Friday")//last sentence without punctuation
);
?>
2. Creating an array
Compact ()
Compact () function--converts one or more variables (containing arrays) to an array: the array compact (mixed $varname [, mixed $ ...]).
Copy CodeThe code is as follows:
<? 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 arrays and, of course, to array variables. Its argument is the name of the variable, not the full name. The opposite function is that extract () functions as the name implies to convert an array to a single string, a key value as its string names, and an array value as the value of a string.
Operation Result:
Copy CodeThe code is as follows:
Array (
[Number] = 1,3,5,7,9
[string] = I ' m phper
[array] = = Array ([0] = and [1] = = = =)
)
Array_combine ()
Array_combine ()--two arrays are re-formed into an array, one for key values: Array array_combine (array $keys, array $values)
Copy CodeThe code is as follows:
<? Php
$number = Array ("1", "3", "5", "7", "9");
$array = Array ("I", "Am", "A", "PHP", "er");
$newArray = Array_combine ($number, $array);
Print_r ($newArray);
?>
Array_combine function not much to say, who read all understand.
Operation Result:
Array ([1] = I [3] = Am [5] = A [7] = = PHP [9] = er)
Range ()
The range () function--Creates an array of the specified range:
Copy CodeThe code is as follows: <? Php
$array 1 = range (0,100,10),//0 is the starting value, 100 is the end value, and 10 is a stepping value (the default stepping value is 1).
Print_r ($array 1);
echo "<br/>";
$array 2 = Range ("A", "Z");
Print_r ($array 2);
echo "<br/>";
$array 3 = range ("Z", "a");
Print_r ($array 3);
?>
Array_fill ()
Array_fill () Function--fills the array function:
Copy CodeThe code is as follows: <? Php
$array = range (1,10);
$fillarray = Range ("A", "D");
$arrayFilled = Array_fill (0,5, $fillarray);//The $fillarray here can be a string, such as "test".
echo "<pre>";
Print_r ($arrayFilled);
echo "</pre>";
$keys = Array ("string", "2", 9, "SDK", "PK");
$array 2 = Array_fill_keys ($keys, "testing");
echo "<pre>";
Print_r ($array 2);
echo "</pre>";
?>
Operation Result:
Copy CodeThe code is as follows: Array
(
[0] = = Array
(
[0] = a
[1] = b
[2] = C
[3] = d
)

[1] = = Array
(
[0] = a
[1] = b
[2] = C
[3] = d
)

[2] = = Array
(
[0] = a
[1] = b
[2] = C
[3] = d
)

[3] = = Array
(
[0] = a
[1] = b
[2] = C
[3] = d
)

[4] = = Array
(
[0] = a
[1] = b
[2] = C
[3] = d
)

)
Array
(
[String] = Testing
[2] = testing
[9] = Testing
[SDK] = Testing
[PK] = Testing
)
3. Iterating the array
foreach traversal
foreach (array_expression as $value) {}
foreach (array_expression as $key = $value) {}
Copy CodeThe code is as follows:
<? Php
$speed = Array (50,120,180,240,380);
foreach ($speed as $keys = = $values) {
echo $keys. " = ". $values." <br/> ";
}
?>
Operation 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 example
Copy CodeThe code is as follows: <? Php
$staff = Array (
Array ("Name", "Gender", "age"),
Array ("Xiao Zhang", "male", 24),
Array ("Xiao 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
Copy CodeThe code is as follows: <? Php
$speed = range (0,220,20);
for ($i =0; $i <count ($speed); $i + +) {
echo $speed [$i]. " ";
}
?>
Operation Result:
0 20 40 60 80 100 120 140 160 180 200 220
4. Pointer manipulation of arrays
The functions involved include reset, prev, end, next, current, each.
Example one: Next and prev
Copy CodeThe code is as follows: <? Php
$speed = range (0,220,20);
Echo current ($speed);//Output The value of the present position (at the beginning of the array)
$i = rand (1,11);
while ($i-) {
Next ($speed);//The pointer moves backwards from the current position one
}
Echo current ($speed);//Output The value of the present position
echo "<br/>";
Echo prev ($speed);//Output previous position array value
echo "<br/>";
echo Reset ($speed);//Resets the pointer to the array and points the pointer to the starting position
echo "<br/>";
Echo End ($speed);//Output The last position of the array value
echo "<br/>";
?>
Operation Result:
0220
200
0
220
Example two: Each function pointer operation
Copy CodeThe code is as follows: <? Php
$speed = range (0,200,40);
echo "Each implementation pointer moves down <br/>";
echo "0-block speed is". Current ($speed). " <br/> ";
echo "1-block speed is". Current ($speed). " <br/> ";
echo "2-block speed is". Current ($speed). " <br/> ";
echo "3-block speed is". Current ($speed). " <br/> ";
echo "4-block speed is". Current ($speed). " <br/> ";
echo "5-block speed is". Current ($speed). " <br/> ";
echo "uses each function to implement array pointer movement, array traversal <br/>";
Reset ($speed);//Here is the array pointer to the top of the array
while (list ($key, $value) =each ($speed)) {
echo $key. " = ". $value." <br/> ";
}
?>
Operation Result:
Copy CodeThe code is as follows: Each implementation pointer moves down
The speed of the 0 block is 0.
The speed of the 1 block is 40.
The speed of the 2 block is 80.
The speed of the 3 block is 120.
The speed of the 4 block is 160.
The speed of the 5 block is 200.
Use each function to move the array pointer, and to iterate through the array
0=>0
1=>40
2=>80
3=>120
4=>160
5=>200
5. Addition and deletion of arrays
Adding array members
Instance one: $num [] = value is appended directly to the end of the array:
[Code]<? Php
$num = Array (1=>80,2=>120,3=>160);
echo "Add array member <br/> using expression";
$num []=240;
Print_r ($num);
?>
Operation Result:
To add an array member using an expression
Array ([0] = [1] = [2] = [3] = 240)
Example two: Array_pad function, array array, optional append
Copy CodeThe code is as follows:
<? Php
$num = Array (1=>80,2=>120,3=>160);
$num = Array_pad ($num, 4,200);
echo "Add member <br/> to the end of the array using the Array_pad function";
Print_r ($num);
echo "<br/>array_pad can also fill the array header <br/>";
$num = Array_pad ($num, -8,40);
Print_r ($num);
?>
Operation Result:
To add a member to the tail of an array using the Array_pad function
Array ([0] = [1] = [2] = [3] = 200)
Array_pad can also populate the array header
Array ([0] = + [1] = + [2] = + [3] = [4] [5] [6] [7] = [+] = 200]
Example three: Append to stack operation (Array_push):
Copy CodeThe code is as follows: <? Php
$num = Array (1=>80,2=>120,3=>160);
Array_push ($num, 200,240,280);//You can append it yourself, add it directly to the end of the array
Print_r ($num);
?>
Operation Result:
Array ([1] = [2] = [3] = [4] = [5] = [6] = 280)
Example four: Array_unshift () adds an array member at the beginning
Copy CodeThe code is as follows:
<? Php
$num = Array (1=>80,2=>120,3=>160);
Array_unshift ($num, 0,40);//You can append it yourself, add it directly to the end of the array
Print_r ($num);
?>
Operation Result:
Array ([0] = 0 [1] = [2] = [3] = [4] = 160)
Note: After using the Array_unshift () function, the array's key values will start at 0!
Subtract array members
Instance one: the unset () command deletes an array member or array:
Copy CodeThe code is 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 "unset command cannot delete entire array";
}else{
echo "unset command can delete array";
}
?>
Run Result: (Run error and description array also deleted, no longer present)
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
unset command cannot delete entire array
Example two: Array_splice () function to delete an array member
Copy CodeThe code is as follows: <?php
$a =array ("Red", "green", "blue", "yellow");
Count ($a); Get 4
Array_splice ($a, 1, 1); Delete the second element
Count ($a); Get 3
echo $a [2]; Get Yellow
echo $a [1]; Get Blue
?>
Example three: Array_unique delete duplicate values in an array:
Copy CodeThe code is as follows:
<?php
$a =array ("Red", "green", "blue", "yellow", "blue", "green");
$result = Array_unique ($a);
Print_r ($result);
?>
Operation Result:
Array ([0] = red [1] = green [2] = = Blue [3] = yellow)
Example four: Array_merge, Array_merge_recursive merged array
Copy CodeThe code is as follows: <?php
$array 1 = Array ("r" = "Red", 1,2,3,4);
$array 2 = Array ("b" = "blue", 4=>5,6,7,8,9);
$array 3 = Array ("r" = "read", 4=>10,2=>11);
$array 4 = Array (
Array (4=>10),
Array (7=>13)
);
$array 5 = Array (
Array (4=>11),
Array (6=>12)
);
$result = Array_merge ($array 1, $array 2, $array 3, $array 4, $array 5);
echo "<pre>";
Print_r ($result);
echo "</pre>";
$result = array_merge_recursive ($array 1, $array 2, $array 3, $array 4, $array 5);
echo "<pre>";
Print_r ($result);
echo "</pre>";
?>
Operation Result:
Copy CodeThe code is as follows: 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
[Ten] + 11
[one] = = Array
(
[4] = 10
)

[+] = Array
(
[7] = 13
)

[+] = Array
(
[4] = 11
)

[+] = 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
[Ten] + 11
[one] = = Array
(
[4] = 10
)

[+] = Array
(
[7] = 13
)

[+] = Array
(
[4] = 11
)

[+] = Array
(
[6] = 12
)

)
Note: 1. The Array_merge key name is the number that will be re-indexed, and when the same string key name is encountered, the following will overwrite the previous one. 2. The role of the array_merge_recursive function is to synthesize an array of key-list elements of the same string.
6. Key and value operations for arrays
Instance one: In_array () detects if a value exists in the array
Copy CodeThe code is as follows:
<?php
$array = range (0,9);
if (In_array (9, $array)) {
echo "exists in array";
}
?>
Run Result: the array exists
Example two: Key () Gets the current key name of the array:
Copy CodeThe code is as follows:
<?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, range (0-8), and no result is shown.
Example three: the list () function assigns the values in the array to the specified variable:
Copy CodeThe code is as follows: <? Php
$staff = Array (
Array ("Name", "Gender", "age"),
Array ("Xiao Zhang", "male", 24),
Array ("Xiao 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>";
?>
Example four: Array_flip () swaps the key values and values of an array:
Copy CodeThe code is as follows:
<? Php
$array = Array ("Red", "blue", "yellow", "Black");
Print_r ($array);
echo "<br/>";
$array = Array_flip ($array);
Print_r ($array);
?>
Operation Result:
Array ([0] = red [1] = blue [2] = yellow [3] = Black)
Array ([red] = 0 [Blue] = 1 [YELLOW] = 2 [Black] + 3)
Copy CodeThe code is as follows:
<? Php
$array = Array ("Red", "blue", "yellow", "Black");
$result = Array_keys ($array);
Print_r ($result);
echo "<br/>";
$result = Array_values ($array);
Print_r ($result);
?>
Operation Result:
Array ([0] = 0 [1] = 1 [2] = 2 [3] = 3)
Array ([0] = red [1] = blue [2] = yellow [3] = Black)
Example six: Array_search () search value:
Copy CodeThe code is as follows:
<? Php
$array = Array ("Red", "blue", "yellow", "Black");
$result = Array_search ("Red", $array);
if (($result = = = NULL)) {
echo "There is no value red";
}else{
echo "existence numerical $result";
}
?>
Result: There is a value of 0
The value returned by the function Array_search () may be false or 0 or null, so be careful to use "= = =" When judging
7. Sorting of arrays
Example one: Sort (), Rsort ()/asort (), and Arsort () are sorted by array:
Copy CodeThe code is as follows:
<? Php
$array = Array ("B", "C", "D", "a");
Sort ($array);//from Low to high
Print_r ($array);
echo "<br/>";
Rsort ($array);//Reverse sort
Print_r ($array);
?>
Results:
Array ([0] = a [1] = b [2] = = c [3] = + D)
Array ([0] = + d [1] = c [2] = = b [3] = a)
The sort (), rsort () function sorts the array from low to high, and returns the result as a bool value;
The Asort (), Arsort () functions are sort of reserved key values, and the key values are not re-indexed after sorting.
Example two: Disrupting the array order--shuffle () function:
Copy CodeThe code is as follows:
<? Php
$array = Array ("A", "B", "C", "D");
Shuffle ($array);//low to high sort
Print_r ($array);
?>
The result is a dynamic result:
Array ([0] = + c [1] = a [2] + d [3] = b)
The result of the shuffle is a bit random meaning that each refresh is different.
Example three: Array_reverse () array Reverse:
Copy CodeThe code is as follows:
<? Php
$array = Array ("D", "B", "A", "C");
$array = Array_reverse ($array);//low to high sort
Print_r ($array);
?>
Operation Result:
Array ([0] = c [1] = a [2] = = b [3] + D)
Example four: Natural sorting algorithm--natsort () and Natcasesort ();
Copy CodeThe code is as follows:
<? Php
$array = Array ("Sort2", "Sort5", "Sort1", "sort4");
Natsort ($array);//low to high sort
Print_r ($array);
echo "<br/>";
Natcasesort ($array);
Print_r ($array);
?>
Results:
Array ([1] = SORT5 [2] = sort1 [0] = = sort2 [3] = = SORT4)
Array ([2] = sort1 [0] = sort2 [3] = = SORT4 [1] = = SORT5)
Natsort (), Natcasesort () is a natural sort of array, which uses the normal sorting algorithm of numbers. Natcasesort ignores case.
Example five: Sorting an array of key values Ksort ():
Copy CodeThe code is as follows:
<? Php
$array = Array (1=> "Sort2",4=> "Sort5",2=> "Sort1",3=> "Sort4");
Ksort ($array);//low to high sort
Print_r ($array);
?>
Results:
Array ([1] = Sort2 [2] = Sort1 [3] = = SORT4 [4] = = SORT5)
Note: the Ksort () function re-established the index.
8. Other uses of arrays
Copy CodeThe code is as follows:
cout ($array)--------number of cells in the statistics array
Array_diff ($array 1, $array 2)----------A different point between the statistical arrays, returns the first array and none in the second array.
ARRAY_DIFF_ASSOC ($array 1, $array 2)---------with Array_diff (), except that it also compares the key values
Array_diff_key ($array 1, $array 2)------------Compare key values
Array_product ($array)-----------returns the product of all the numbers of an array
Array_sum ($array)--------------of all values and
Array_rand ($array, $n)----------take $n values in the $array array, return the array
Array_intersect ($array 1, $array 2)----------------get the intersection of two arrays
ARRAY_INTERSECT_ASSOC ($array 1, $array 2)---------------The comparison of key values on the basis of Array_intersect
Array_intersect_key ($array 1, $array 2)-----------------Compare the intersection of two array key values
Summarize
The use of arrays is critical in PHP, because PHP has no pointers, so the array takes on a lot of data manipulation tasks. Learn the array, in order to get the handy PHP application, listed here are commonly used PHP array related functions and usage, welcome to learn together!

PHP Array Operations summary PHP array usage tips

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.