PHP Array Operations Summary php array tips _ PHP Tutorial

Source: Internet
Author: User
Tags array definition shuffle
PHP array operation 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 of my learning. I will take this note to facilitate future authentication. 1. an array defines an array, which is an important method in PHP Data applications. PHP has a large number of array functions. The following is a summary of my learning. I will take this note to facilitate future authentication.
1. array definition
The array definition uses the array () method to define an empty array:

The code is as follows:


$ 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 $...]).

The code is as follows:


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

The code is as follows:


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)

The code is as follows:


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

The code is as follows:

$ 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"
";
$ Array2 = range ("A", "Z ");
Print_r ($ array2 );
Echo"
";
$ Array3 = range ("z", "");
Print_r ($ array3 );
?>


Array_fill ()
Array_fill () function -- fill array function:

The code is as follows:

$ Array = range (1, 10 );
$ Fillarray = range ("a", "d ");
$ ArrayFilled = array_fill (, $ fillarray); // $ fillarray can be a string, such as "test ".
Echo"

"; 
print_r ($arrayFilled);
echo "
";
$ Keys = array ("string", "2", 9, "SDK", "PK ");
$ Array2 = array_fill_keys ($ keys, "testing ");
Echo"
"; 
print_r ($array2);
echo "
";
?>


Running result:

The code is as follows:

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 ){}

The code is as follows:


$ Speed = array (50,120,180,240,380 );
Foreach ($ speed as $ keys => $ values ){
Echo $ keys. "=>". $ values ."
";
}
?>


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

The code is as follows:

$ Staff = array (
Array ("name", "gender", "age "),
Array ("Xiao Zhang", "male", 24 ),
Array ("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

The code is as follows:

$ Speed = range (0,220, 20 );
For ($ I = 0; $ 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

The code is as follows:

$ 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"
";
Echo prev ($ speed); // output the array value in the previous position
Echo"
";
Echo reset ($ speed); // reset the pointer to the starting position.
Echo"
";
Echo end ($ speed); // output the array value at the last position
Echo"
";
?>


Running result:
0220
200
0
220
Example 2: each function pointer operation

The code is as follows:

$ Speed = range (0,200, 40 );
Echo "each implement pointer move down
";
Echo "the speed of 0 blocks is". current (each ($ speed ))."
";
Echo "1 speed is". current (each ($ speed ))."
";
Echo "2 speed is". current (each ($ speed ))."
";
Echo "the speed of 3 blocks is". current (each ($ speed ))."
";
Echo "the speed of 4 blocks is". current (each ($ speed ))."
";
Echo "the speed of 5 blocks is". current (each ($ speed ))."
";
Echo "use the each function to move the array pointer and traverse the array
";
Reset ($ speed); // The array pointer points to the first part of the array.
While (list ($ key, $ value) = each ($ speed )){
Echo $ key. "=>". $ value ."
";
}
?>


Running result:

The code is as follows:

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] $ Num = array (1 => 160 =>, 3 => );
Echo "using expressions to add array members
";
$ 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

The code is as follows:


$ 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.
";
Print_r ($ num );
Echo"
Array_pad can also fill the array header
";
$ 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 ):

The code is as follows:

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

The code is as follows:


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

The code is 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 "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.

The code is as follows:

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

The code is as follows:


$ 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

The code is as follows:

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

"; 
print_r($result);
echo "
";
$ Result = array_merge_recursive ($ array1, $ array2, $ array3, $ array4, $ array5 );
Echo"
"; 
print_r ($result);
echo "
";
?>


Running result:

The 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
[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.

The code is as follows:


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

The code is as follows:


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

The code is as follows:

$ Staff = array (
Array ("name", "gender", "age "),
Array ("Xiao Zhang", "male", 24 ),
Array ("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
";
?>


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

The code is as follows:


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

The code is as follows:


$ Array = array ("red", "blue", "yellow", "Black ");
$ Result = array_keys ($ array );
Print_r ($ result );
Echo"
";
$ 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:

The code is as follows:


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

The code is as follows:


$ Array = array ("B", "c", "d", "");
Sort ($ array); // sort from low to high
Print_r ($ array );
Echo"
";
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:

The code is as follows:


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

The code is as follows:


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

The code is as follows:


$ Array = array ("sort2", "Sort5", "sort1", "sort4 ");
Natsort ($ array); // sort from low to high
Print_r ($ array );
Echo"
";
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 ():

The code is as follows:


$ 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

The code is as follows:


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


Summary
The use of arrays is crucial in PHP. because PHP does not have pointers, arrays undertake a large amount of data operation tasks. Learning arrays well can make PHP applications handy. all the functions and usage related to PHP arrays are listed here. please study them together!

Bytes. PHP has a large number of array functions. The following is a summary of my learning. I will take this note to facilitate future authentication. 1. array definition array...

Related Article

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.