PHP array using the detailed recommendation _php tips

Source: Internet
Author: User
Tags array definition compact mixed prev rand shuffle
PHP's Array function is numerous, below is my study summary, takes this to remember, facilitates later ...
one, array definition:
The definition of an array is defined using the array () method, and an empty array can be defined:
. Foreach Traversal:
Copy Code code as follows:

<?php
$number = Array (1,3,5,7,9);
Define an empty array
$result = Array ();
$color =array ("Red", "Blue", "green");
Custom Key values
$language = (1=> "中文版",3=> "Chinese",5=> "Franch");
Defining two-dimensional arrays
$two = Array (
"Color" =>array ("Red", "blue"),//ending with a comma
"Week" =>array ("Monday", "Friday")//last sentence without punctuation
);
?>

second, create an array:
The created array contains functions that have a compact (),
1.compact () function-converts one or more variables (including arrays) to an array: the array compact (mixed $varname [, mixed $ ...])
Copy Code code 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 an array, and, of course, to include arrays of variables. The argument is the name of the variable, not the full name.
The opposite function is the extract () function that converts an array to a single string, a key value as its string name, and an array value as the value of the string.
Run Result:
Copy Code code as follows:

Array ([number] => 1,3,5,7,9 [string] => I ' m phper [array] => array ([0] => and [1] => you?)

2.array_combine ()--resets two arrays into an array, one for key values: Array array_combine (array $keys, array $values)
Copy Code code 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 said, who read all understand
Run Result:
Array ([1] => I [3] => Am [5] => A [7] => PHP [9] => er)
3.range () function--Create an array of the specified range: Not much, directly on the example--
Copy Code code as follows:

? Php
$array 1 = range (0,100,10);//0 is the starting value, 100 is the ending value, 10 is the step value (the default step 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);
?>

The default step value for the range () function is 1!
Run Result:
Copy Code code as follows:

Array ([0] => 0 [1] => [2] => [3] => [4] => [5] => [6] => [7] => 8 0 [9] => [=>] Array ([0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [] => K [one] => L [[] => M [] => N [[] => O [] => P [16] = > Q [[] => R [S] => [m] => T [[] => U [] => V [a] => W [a] => X [[] => Y [] => z) Array ([0] => Z [1] => y [2] => x [3] => W [4] => v [5] => u [6] => T [7] => s [8] => R [9] ] => Q [A] => p [one] => o [[] => n [[] => m [] => l [[] => k [[] => J [] => I [a] =&g T h [d] => G [[d] => f [[] => e [d] => D. [a] => C [] => b [] => a)

4.array_fill () function--Populate array functions:
Copy Code code as follows:

? Php
$array = range (1,10);
$fillarray = Range ("A", "D");
$arrayFilled = Array_fill (0,5, $fillarray);//The $fillarray here can be strings, 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>";
?>

Run Result:
Copy Code code 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
)

three, the array of traversal:
1.foreach traversal: foreach (array_expression as $value) {}
foreach (array_expression as $key => $value) {}
Less gossip, above instance:
Copy Code code as follows:

? Php
$speed = Array (50,120,180,240,380);
foreach ($speed as $keys => $values) {
echo $keys. " => ". $values." <br/> ";
}
?>

Run Result:
Copy Code code as follows:

0=>50
1=>120
2=>180
3=>240
4=>380

2.while Loop Traversal:
While loop traversal is generally combined with the list function, the following is an instance
Copy Code code 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 (the list ($keys, $value) = each ($staff)) {
List ($name, $sex, $age) = $value;
echo "<tr><td> $name </td><td> $sex </td><td> $age </td></tr>";
}
echo "</table>";
?>

Run Result:
Name Gender Age
Xiao Zhang Man 24
Xiao Wang Woman 25
Xiao Li Man 23
3.for Loop Traversal:
Copy Code code as follows:

? Php
$speed = range (0,220,20);
for ($i =0; $i <count ($speed); $i + +) {
echo $speed [$i]. " ";
}
?>

Run Result:
Copy Code code as follows:

0 20 40 60 80 100 120 140 160 180 200-220

Four, the array of pointer operation:
Involved functions include reset, prev, end, next, current, each
Example one:
Copy Code code as follows:

? Php
$speed = range (0,220,20);
Echo current ($speed);//Output the value at the position (at the beginning of the array)
$i = rand (1,11);
while ($i-) {
Next ($speed);//The pointer moves backward from the current position
}
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);//Reset the pointer to the array, pointing to the starting position
echo "<br/>";
Echo End ($speed);//Output The array value of the last position
echo "<br/>";
?>

Run Result:
Copy Code code as follows:

0220
200
0
220

Example two: Each function pointer operation
Copy Code code as follows:

? Php
$speed = range (0,200,40);
echo "Each implementation pointer moves down <br/>";
echo "0-block speed is". Current (each ($speed)). <br/> ";
echo "1-block speed is". Current (each ($speed)). <br/> ";
echo "2-block speed is". Current (each ($speed)). <br/> ";
echo "3-block speed is". Current (each ($speed)). <br/> ";
echo "4-block speed is". Current (each ($speed)). <br/> ";
echo "5-block speed is". Current (each ($speed)). <br/> ";
echo "uses each function to implement array pointer movement, array traversal <br/>";
Reset ($speed);//This is to point the array pointer at the top of the array
while (list ($key, $value) =each ($speed)) {
echo $key. " => ". $value." <br/> ";
}
?>

Run Result:
Copy Code code as follows:

Each implementation pointer moves down
0 Gear speed is 0.
1 gear speed is 40.
2 gear speed is 80.
3 Gear speed is 120.
4 Gear speed is 160.
5 gear speed is 200.
Using the each function to move the array pointer, array traversal
0=>0
1=>40
2=>80
3=>120
4=>160
5=>200

The addition and deletion operation of the array:
1. Add an array member: instance one: $num [] = value Direct assignment appended to the end of the array:
Copy Code code as follows:

? Php
$num = Array (1=>80,2=>120,3=>160);
echo "adds an array member <br/> using an expression";
$num []=240;
Print_r ($num);
?>

Run Result:
Using expressions to add array member array ([0] => [1] => [2] => 160 [3] => 240)
Example two: Array_pad function, array array and optional append
Copy Code code as follows:

? Php
$num = Array (1=>80,2=>120,3=>160);
$num = Array_pad ($num, 4,200);
Echo uses the Array_pad function to add members <br/> to the tail of the array;
Print_r ($num);
echo "<br/>array_pad can also populate array header <br/>";
$num = Array_pad ($num, -8,40);
Print_r ($num);
?>

Run Result:
Copy Code code as follows:

Add member array to the end of the array using the Array_pad function ([0] => [1] => [2] => 160 [3] =>) Array_pad can also populate the array header array ([0] => ; [1] => [2] => [3] => [4] => [5] => [6] => 160 [7] => 200)

Example three: Stack operation append (Array_push):
Copy Code code as follows:

? Php
$num = Array (1=>80,2=>120,3=>160);
Array_push ($num, 200,240,280);//Can be appended directly to the end of the array
Print_r ($num);
?>

Run Result:
Array ([1] => [2] => [3] => 160 [4] => [5] => [6] => 280)
Example four: Array_unshift () Adding an array member at the beginning
Copy Code code as follows:

? Php
$num = Array (1=>80,2=>120,3=>160);
Array_unshift ($num, 0,40);//Can be appended directly to the end of the array
Print_r ($num);
?>

Run Result:
Array ([0] => 0 [1] => [2] => [3] => (4) => 160)
Note: the Array_unshift () function uses the key value of the following array to start at 0!
2. Subtract Array Members:
Instance one: unset () command deletes an array member or array:
Copy Code 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 "unset command cannot delete entire array";
}else{
echo "unset command can delete array";
}
?>

Run Result: (Run error and description array also deleted, no longer exists)
Copy Code code as follows:

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

Instance two: Array_splice () function to delete an array member
Copy Code code as follows:

<?php
$a =array ("Red", "green", "blue", "yellow");
Count ($a); Get 4
Array_splice ($a, 1, 1); Delete a second element
Count ($a); Get 3
echo $a [2]; Get Yellow
echo $a [1]; Get Blue
?>

Instance three: Array_unique deletes duplicate values from the array:
Copy Code code as follows:

<?php
$a =array ("Red", "green", "blue", "yellow", "blue", "green");
$result = Array_unique ($a);
Print_r ($result);
?>

Run Result:
Array ([0] => red [1] => green [2] => blue [3] => yellow)
Example four: Array_merge, array_merge_recursive merging arrays
Copy Code code 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>";
?>

Run Result:
Copy Code code 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
)
[of] => Array
(
[7] => 13
)
[A] => 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
)
[of] => Array
(
[7] => 13
)
[A] => Array
(
[4] => 11
)
[=>] Array
(
[6] => 12
)
)

Note: The 1.array_merge key name is a number that will be indexed again, and the following will overwrite the previous one when the same string key name is encountered.
The role of the 2.array_merge_recursive function is to synthesize an array of key list elements of the same string.
The key value and value operation of the array:
Instance one: In_array () detects whether a value exists in the array
Copy Code code as follows:

<?php
$array = range (0,9);
if (In_array (9, $array)) {
echo "exists in array";
}
?>

Run Result:
exists in the array
Instance two: Key () Gets the current key name of the array:
Copy Code code as follows:

<?php
$array = range (0,9);
$num = rand (0,8);
while ($num--)
Next ($array);
$key = key ($array);
Echo $key;
?>

This instance results in a dynamic result, a range (0-8), and does not demonstrate the results.
Example three: the list () function assigns the value in the array to the specified variable:
Copy Code code 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 (the list ($keys, $value) = each ($staff)) {
List ($name, $sex, $age) = $value;
echo "<tr><td> $name </td><td> $sex </td><td> $age </td></tr>";
}
echo "</table>";
?>

Run Result:


Instance four: Array_flip () Exchange the key values and values of the array:
Copy Code code as follows:

? Php
$array = Array ("Red", "blue", "yellow", "black");
Print_r ($array);
echo "<br/>";
$array = Array_flip ($array);
Print_r ($array);
?>

Run Result:
Copy Code code as follows:

Array ([0] => red [1] => blue [2] => yellow [3] => Black)
Array ([red] => 0 [Blue] => 1 [yellow] => 2 [Black] => 3)

Instance five: Array_keys (), array_values () returns all the key values and values in the array:
Copy Code code 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);
?>

Run Result:
Copy Code code as follows:

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

Example six: Array_search () Search values:
Copy Code code as follows:

? Php
$array = Array ("Red", "blue", "yellow", "black");
$result = Array_search ("Red", $array);
if (($result = = NULL)) {
echo "does not exist a value red";
}else{
echo "exists 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
Vii. Sorting of arrays:
Instance one: Sort (), Rsort ()/asort (), Arsort () array of arrays:
Copy Code code as follows:

? Php
$array = Array ("B", "C", "D", "a");
Sort ($array);//from Low to high
Print_r ($array);
echo "<br/>";
Rsort ($array);//Reverse Ordering
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 is sorted from low to high, and the result is bool;
The Asort (), Arsort () function is the sort that preserves the key values, and the key values are not indexed again after sorting.
Example two: Upsetting the array order--shuffle () function:
Copy Code code as follows:

? Php
$array = Array ("A", "B", "C", "D");
Shuffle ($array);//from Low to high order
Print_r ($array);
?>

Results are dynamic results:
Array ([0] => C [1] => a [2] => D [3] => B)
The results of shuffle are somewhat random, and each refresh is different.

Example three: Array_reverse () array Reverse:
Copy Code code as follows:

? Php
$array = Array ("D", "B", "A", "C");
$array = Array_reverse ($array);//from low to high sort
Print_r ($array);
?>

Run Result:
Array ([0] => C [1] => a [2] => b [3] => D)
Example four: Natural sorting algorithm--natsort () and Natcasesort ();
Copy Code code as follows:

? Php
$array = Array ("Sort2", "Sort5", "Sort1", "sort4");
Natsort ($array);//from Low to high order
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, using the normal sorting algorithm of numbers. Natcasesort ignores case.
Instance five: Array of key values sort Ksort ():
Copy Code code as follows:

? Php
$array = Array (1=> "Sort2",4=> "Sort5",2=> "Sort1",3=> "Sort4");
Ksort ($array);//from Low to high order
Print_r ($array);
?>

Results:
Array ([1] => Sort2 [2] => Sort1 [3] => SORT4 [4] => Sort5)
Note: the Ksort () function has been indexed again.
Eight, other uses of the array:
cout ($array)--------count the number of cells in an array
Array_diff ($array 1, $array 2)----------The difference between the statistics array, and returns the one in the first array that is not in the second array.
ARRAY_DIFF_ASSOC ($array 1, $array 2)---------with Array_diff (), but 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)--------------all values and
Array_rand ($array, $n)----------Remove $n values in the $array array, and return the array
Array_intersect ($array 1, $array 2)----------------get the intersection of two arrays
ARRAY_INTERSECT_ASSOC ($array 1, $array 2)---------------Key-value comparisons on a array_intersect basis
Array_intersect_key ($array 1, $array 2)-----------------Compare the intersection of two 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 use PHP handy, here are the commonly used PHP array related functions and usage, welcome to study together!

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.