PHP Array usage tips and operations summary

Source: Internet
Author: User
Tags compact shuffle
arrays, which can be said to be a more important way of data application in PHP. PHP array functions are numerous, below is a few summary, take this to remember, easy to later.

1. Array definitions
The definition of an array is defined using the array () method, and an empty array can be defined:
$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 $ ...]).
$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:

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)
$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:
$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
";
$array 2 = Range ("A", "Z");
Print_r ($array 2);
echo "
";
$array 3 = range ("Z", "a");
Print_r ($array 3);
?>
Array_fill ()
Array_fill () Function--fills the array function:
$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 "



echo "
";
$keys = Array ("string", "2", 9, "SDK", "PK");
$array 2 = Array_fill_keys ($keys, "testing");
echo "


echo "
";
?>
Operation Result:
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) {}

$speed = Array (50,120,180,240,380);
foreach ($speed as $keys = = $values) {
echo $keys. " = ". $values."
";
}
?>
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
$staff = Array (
Array ("Name", "Gender", "age"),
Array ("Xiao Zhang", "male", 24),
Array ("Xiao Wang", "female", 25),
Array ("Xiao Li", "male", 23)
);
echo "






"; while (list ($keys, $value) = each ($staff)) {list ($name, $sex, $age) = $value; echo " "; } echo "
$name $sex $age
";
?>
For loop traversal
$speed = range (0,220,20);
for ($i =0; $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
$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 "
";
Echo prev ($speed);//Output previous position array value
echo "
";
echo Reset ($speed);//Resets the pointer to the array and points the pointer to the starting position
echo "
";
Echo End ($speed);//Output The last position of the array value
echo "
";
?>
Operation Result:
0220
200
0
220
Example two: Each function pointer operation
$speed = range (0,200,40);
echo "Each implementation pointer moves down
";
echo "0-block speed is". Current ($speed). "
";
echo "1-block speed is". Current ($speed). "
";
echo "2-block speed is". Current ($speed). "
";
echo "3-block speed is". Current ($speed). "
";
echo "4-block speed is". Current ($speed). "
";
echo "5-block speed is". Current ($speed). "
";
echo "uses each function to move an array pointer, to iterate over the array
";
Reset ($speed);//Here is the array pointer to the top of the array
while (list ($key, $value) =each ($speed)) {
echo $key. " = ". $value."
";
}
?>
Operation Result:
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] $num = Array (1=>80,2=>120,3=>160);
echo "Adding an array member using an 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

$num = Array (1=>80,2=>120,3=>160);
$num = Array_pad ($num, 4,200);
echo "Use the Array_pad function to add members to the end of the array
";
Print_r ($num);
echo "
Array_pad can also populate the array header
";
$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):
$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

$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 the code code as follows: $num = Array_fill (0,5,rand (1,10));
Print_r ($num);
echo "
";
Unset ($num [4]);
Print_r ($num);
echo "
";
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
$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:

$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
$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 "



echo "
";
$result = array_merge_recursive ($array 1, $array 2, $array 3, $array 4, $array 5);
echo "


echo "
";
?>
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

$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:

$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:
Array ("Xiao Li", "male", 23)
);
echo "






"; while (list ($keys, $value) = each ($staff)) {list ($name, $sex, $age) = $value; echo " "; } echo "
$name $sex $age
";
?>


Example four: Array_flip () swaps the key values and values of an array:

$array = Array ("Red", "blue", "yellow", "Black");
Print_r ($array);
echo "
";
$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)

$array = Array ("Red", "blue", "yellow", "Black");
$result = Array_keys ($array);
Print_r ($result);
echo "
";
$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:

$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:

$array = Array ("B", "C", "D", "a");
Sort ($array);//from Low to high
Print_r ($array);
echo "
";
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:

$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:

$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 ();

$array = Array ("Sort2", "Sort5", "Sort1", "sort4");
Natsort ($array);//low to high sort
Print_r ($array);
echo "
";
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 ():

$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

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

The above describes the use of PHP array techniques and operations summary, including the content of the article, I hope that the PHP tutorial interested in a friend helpful.

  • 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.