Learn PHP's array summary "experience", PHP array Summary _php tutorial

Source: Internet
Author: User
Tags learn php random shuffle shuffle

Learn PHP's array summary "experience", PHP array Summary


PHP has a lot of functions for arrays, which makes it easy to manipulate arrays.

Defined:

The array contains two items per entity: Key and value, which can be obtained by querying the key. These keys can be numeric (numerical) Keys or association (associative) keys. Numeric keys are not really associated with values, they are just the positions of values in the array.

PHP provides a lot of ways to iterate through an array, not using an association key or a numeric key, all depending on a property called an array pointer.

Create an array

PHP does not need to specify its size when creating an array, because PHP is a loose language, so it does not need to be declared before the array is used. Although there is no limit, PHP still provides formal and informal array declaration methods.

Refer to each element of the PHP array, indicated by a pair of brackets. Arrays have no size limits, so you can create arrays simply by creating a reference, for example:

$state [0]= ' 111 '; $state [1]= ' 222 ';

If the index value is a numeric index and is incremented, the index value can also be omitted at creation time.

$state [] = ' 111 '; $state [] = ' 222 ';

You can create an array using array (), such as:

$state =array (' 111 ', ' 222 '); $state =array (' one ' + ' 111 ', ' one ' = ' 222 ');

Use list () to extract the array, for example:

$state = Array (' One ', ' n ', ' three '); list ($one, $two, $three) = $state;

The three values in the array are assigned to the $one, $two, $three, and can be output directly.

Populate the array with predefined value ranges, for example:

$num = Range (1, 6);//similar to $num =array (1, 2, 3, 4, 5, 6); selectable parity: $num =range (1, 6, 2);

$num = Array (1, 3, 5), selectable letters: $ch =range ("A", "F"),//$ch = Array ("A", "B", "C", "D", "E", "F");

Output array

The most common way to output array content is to iterate through the individual array keys and output the corresponding values.

The foreach () function can easily traverse an array to get each value and key.

The Print_r () function makes it easy to output the contents of an array to the screen. The Prinf_r () function takes a variable and sends its contents to the standard output, returning true on success, or false.

Test array

You know whether a particular variable is an array by using the Is_array () function.

The Is_array () function determines whether a variable is an array, or returns True if it is, otherwise false. Even if the array contains only one value, it will be considered an array.

Adding and removing array elements

PHP provides a number of functions for enlarging and shrinking arrays, which facilitates the simulation of various queue implementations.

To add an element to the array header:

The Array_unshift () function adds elements to the array header. All existing numeric keys are modified accordingly to reflect their new position in the array, but the association keys are not affected.

$state = Array (' One ', ' n ', ' Array_unshift '); ($state, ' xx ');//$state = array (' 00 ', ' 11 ', ' 22 ', ' 33 ');

Add an element at the end of the array:

The Array_push () function adds the value to the end of the array and returns the total number of elements in the array after the new value is added. At the same time, by passing this variable as an input parameter to this function, the array is pressed into multiple variables (elements) in the form of:

$state = Array (' 1 ', ' 2 '); Array_push ($state, ' 3 ');//$state = Array (' 1 ', ' 2 ', ' 3 ');

To delete an element from an array header:

The Array_shift () function deletes and returns the first element found in the array. As a result, if you are using a numeric key, all corresponding values are moved down, and the array using the associated key is not affected in the form of:

$state = Array (' 1 ', ' 2 '); Array_shift ($state);//$state = Array (' 2 ');

To delete an element from the end of an array:

The Array_pop () function deletes and returns the last element of the array, in the form of:

$state = Array (' 1 ', ' 2 '); Array_pop ($state);//$state = Array (' 1 ');

Locating array elements

To search for an array:

The In_array () function searches the array for a specific value, returns True if the value is found, or false, in the form of the following:

$user = Array (' 111 ', ' 222 ', ' 333 '); $str = ' 111 '; if (In_array ($str, $user)) {echo ' Yes ';} Else{echo ' no ';}

The third parameter, strict, is optional, forcing In_array () to consider the type when searching.

Search for associative arrays:

If a specified key is found in an array, the function array_key_exists () returns True, otherwise false is returned. The form is as follows:

$arr = Array (' One ' = ' 1 ', ' one ' = ' 2 ', ' three ' = ' 3 '), if (Array_key_exists (' n ', $arr)) {echo ' Yes ';} Else{echo ' no ';}

Search for associative arrays:

The Array_search () function searches for a specified value in an array, returns the corresponding value if found, otherwise returns false, in the form of the following:

$arr = Array (' One ' = ' 1 ', ' one ' = ' 2 ', ' three ' = ' 3 '), if (Array_search (' 1 ', $arr)) {echo ' Yes ';} Else{echo ' no ';}

Get array Key:

The Array_key () function returns an array that contains all the keys found in the searched array in the following form:

$arr = Array (' One ' = ' 1 ', ' one ' = ' 2 ', ' three ' = ' 3 '); $keys = Array_keys ($arr); Var_dump ($keys);//array (3) {[0]= > String (3) "One" [1]=> string (3) "One" [2]=>string (5) "three"}

Get Array Value:

The Array_values () function returns all the values in an array and automatically provides an array index for the returned array, in the form of the following:

$arr = Array (' One ' = ' 1 ', ' one ' = ' 2 ', ' three ' = ' 3 '); $values = Array_values ($arr); Var_dump ($values);//array (3 ) {[0]=> string (1) "1" [1]=> string (1) "2" [2]=>string (1) "3"}

Iterating through an array

Typically, you need to iterate through the array and get the keys or values (or both), and PHP provides some functions to meet the requirements. Many functions can accomplish two tasks, not only to get the key or value of the current pointer position, but also to move the pointer down an appropriate position.

Gets the current array key:

The key () function returns the keys in the array where the current pointer is located, in the form of the following:

$arr = Array (' One ' = ' 1 ', ' one ' + ' 2 ', ' three ' = ' 3 '); $key = key ($arr); Var_dump ($key);//string (3) "One"

Note: Each time you call key (), the pointer is not moved.

Gets the current array value:

The current () function returns the array value in the array where the pointer is currently located. The form is as follows:

$arr = Array (' One ' = ' 1 ', ' one ' + ' 2 ', ' three ' = ' 3 '); $value = current ($arr); Var_dump ($value);//string (1) "1"

Gets the current array key and value:

The each () function returns the current key/value pair of the array and advances the pointer to a position in the following form:

$arr =array (' one ' = ' 1 ', ' one ' + ' 2 ', ' three ' = ' 3 '), Var_dump (each ($arr));//array (4) {[1]=> string (1) "1" [" Value "]=> string (1)" 1 "[0]=> string (3)" One "[" Key "]=>string (3)" One "}

The returned array contains 4 keys, the key 0 and key keys contain the key names, and key 1 and value contain the corresponding data. Returns False if each () is executed before the pointer is at the end of the array.

To move an array pointer:

1) Move the pointer to the next array position

The next () function returns the array value immediately next to the current array pointer, or False if the pointer is in the last position of the array.

$arr = Array (' One ' = ' 1 ', ' one ' = ' 2 ', ' three ' = ' 3 '); echo next ($arr); Output 2echo Next ($arr); Output 3

2) Move the pointer to the previous array position

The prev () function returns the array value that is located in the previous position of the current pointer and returns False if the pointer is in the first position of the array.

3) Move the pointer to the first array position

The reset () function is used to set the array pointer back to the beginning of the array, and if you need to view or manipulate an array multiple times in a script, this function is often used, and this function is often used at the end of a sort.

4) Move the pointer to the last array position

The end () function moves the pointer to the last position of the array and returns the last element.

To pass an array value to a function:

The Array_walk () function passes individual elements in an array to a user-defined function. This function will work if you need to complete a specific action on each array element. The form is as follows:

FunctionTest ($value, $key) {echo$value. ' '. $key. ';} $arr = Array (' One ' = ' 1 ', ' both ' = ' 2 ', ' three ' = ' 3 '); Array_walk ($arr, ' test ');//1 ONE//2 TWO//3 Three

If you use a multidimensional array, the array_walk_recursive () function introduced in PHP5 can recursively apply a user-defined function to each element in the array.

Determining the size and element uniqueness of an array

Determine the size of the array:

The count () function returns the total number of values in the array

If the optional mode parameter (set to 1) is activated, the array will be recursive counting statistics elements. Count (Array (), 1);

Note: the sizeof () function is the alias of Count (). Functionally consistent.

Statistics the frequency at which array elements appear:

The Array_count_values () function returns an array containing the associated key/value pairs, in the form of the following:

$arr = Array (' A ', ' B ', ' C ', ' a '), $res = Array_count_values ($arr);p Rint_r ($res),//array ([A] = 2 [b] = 1 [c] = 1 )

The value indicates how often it occurs.

To determine a unique array element:

The Array_unique () function removes all duplicate values in the array, returning an array of unique values, in the form of the following:

$arr = Array (' A ', ' B ', ' C ', ' a '); $res = Array_unique ($arr);p rint_r ($res);//array ([0] = a [1] = b [2] = c)

The optional parameter sort_flags (new in PHP5.2.9) determines how the array keys are sorted. By default, values are sorted as strings, but they can also be sorted by numeric values (Sort_numeric), or by using the PHP default sorting method (Sort_regular), and also by the localized environment (sort_locale_string).

Array sorting

To sort the inverse array elements:

The Array_reverse () function resets the order of the elements in the array in the following form:

$arr = Array (' A ', ' B ', ' C '); $res = Array_reverse ($arr);p rint_r ($res);//array ([0] = C [1] = b [2] = A)

If the optional parameter Preserve_keys is set to true, the key mapping is maintained, otherwise the values of the re-placement correspond to the corresponding keys at the previous position.

$arr = Array (' A ', ' B ', ' C '); $res = Array_reverse ($arr, True);p Rint_r ($res);//array ([2] = C [1] = b [0] = A)

Permutation array keys and values:

The Array_flip () function replaces the role of the key and its corresponding value in the array in the form of the following:

$arr = Array (' A ', ' B ', ' C '), $res = Array_flip ($arr);p Rint_r ($res),//array ([A] = 0 [B] = 1 [c] + 2)

Array sorting:

The sort () function sorts the array by the order of the values from lowest to highest, in the form of the following:

The sort () function does not return the sorted array, but instead it simply "in place" sorts the arrays, regardless of the result, no value is returned. The sort_flags parameter is optional and modifies the default behavior of the function based on the value specified by this parameter.

1) sort_numeric, sorted by value. is useful for sorting integers and floating-point numbers.

2) sort_regular, sort the elements according to the corresponding ASCII values.

3) sort_string, sort the elements in the correct order close to what people perceive.

The Asort () function is required to keep the array ordering under the initial key/value corresponding condition.

The Assort () function is the same as the sort () function, sorted in ascending order, except that it maintains a key/value association, in the form of the following:

$arr = Array (' C ', ' B ', ' A '), $res = $arr;p rint_r ($arr), sort ($arr);p Rint_r ($arr), Asort ($res);p rint_r ($res);//array ([0]  + c [1] = B [2] + a) array ([0] = a [1] = B [2] + c) Array ([2] = a [1] = b [0] + = C )

Sort an array in reverse order

The Rsort () function is the same as the sort () function, except that it sorts the array elements in reverse order (descending).

If you use the optional sort_flags parameter, the specific sort behavior is determined by this value.

Sort an array in reverse order with a key/value pair maintained

As with Asort (), the Arsort () function keeps the key/value association, but it sets the array up in reverse order

$arr = Array (' C ', ' B ', ' A ', ' D '), Arsort ($arr);p rint_r ($arr);//array ([3] = + D [0] = c [1] = = B [2] = A)

If you use the optional sort_flags parameter, the specific sort behavior is determined by this value.

Array Natural Sorting

The Natsort () function provides a sort mechanism that is equivalent to people's usual use.

The typical algorithms are sorted as follows:

P1.jpg,p10.jpg, P2.jpg, p20.jpg

Use the Natsort () function as follows:

P1.jpg,p2.jpg, P10.jpg, p20.jpg

Case-insensitive natural sorting

Such as:

Picture1.jpg,picture10.jpg, Picture2.jpg, picture20.jpg

Sort key values in array

Ksort () function keys are sorted by array, and if successful returns TRUE, the failure returns false

Sort the array keys in reverse order

The operation of the Krsort () function is the same as the Ksort (), and the keys are sorted in reverse order.

Sort by user-defined rules

The Usort () function provides an alternative sorting method that can be ordered using the user-defined comparison algorithm specified in the function. This function is required if you need to sort the data in some way, and any built-in sort functions for PHP do not provide support.

Array merging, splitting, joining, and decomposition

Merging arrays

The Array_merge () function merges the arrays together to return an array of unions. The resulting array starts with the first input array parameter, appended in the order in which the array parameters appear later. The form is as follows:

$arr = Array (' C ', ' B ', ' A ', ' D '); $arr 1= Array (' 1 ', ' 2 ', ' 3 ', ' 4 '); $arr 2= Array_merge ($arr, $arr 1);p Rint_r ($arr 2);//array ( [0] = = C [1] = B [2] = = A [3] + D [4] = 1 [5] = 2 [6]=> 3 [7] = 4)

Recursive append array

The array_merge_recursive () function is the same as Array_merge (), which merges two or more arrays together to form an array of unions. The difference between the two is that when a key in an input array already exists in the result array, the function takes a different approach. Array_merge () overrides the previously existing key/value pair, replaces it with the key/value pair in the current input array, and array_merge_recursive () merges two values together to form a new array with the original key as the array name. The form is:

$arr = Array (' One ' = ' C ', ' one ' = ' B '); $arr 1= Array (' three ' = ' 1 ', ' one ' = ' 2 '); $arr 2= array_merge_recursive ($arr, $arr 1);p Rint_r ($arr 2);//array ([One] = Array ([0] = B [1] = 2) [three] + 1)

Merging two arrays

The Array_combine () function generates a new array that consists of a set of committed keys and corresponding values in the form of:

$arr = Array (' A ', ' B '); $arr 1= Array (' 1 ', ' 2 '); $arr 2= array_combine ($arr, $arr 1);p Rint_r ($arr 2);//array ([A] = 1 [b] =& Gt 2)

Splitting a fraction group

The Array_slice () function returns a portion of the array, starting with the key offset and ending at the offset+length position.

When offset is positive, the split starts at offset from the beginning of the array, and if offset is a negative value, the split starts at the offset position at the end of the array. If the optional parameter length is omitted, the split starts at offset and continues to the last element of the array. If length is given and is positive, the offset+length position ends at the beginning of the array. Conversely, if length is given and is negative, the count-|length| position at the beginning of the array ends. The form is as follows:

$arr = Array (' A ', ' B ', ' C ', ' D '); $arr 1= array_slice ($arr, 2, 1);p Rint_r ($arr 1);//array ([0] = C)

To find the intersection of arrays

The Array_intersect () function returns an array that retains the key, which consists only of the values that appear in the first array and that appear in each of the other input arrays. The form is as follows:

$arr = Array (' A ', ' B ', ' C ', ' D '); $arr 1= Array (' A ', ' B ', ' E '); $arr 2= Array (' A ', ' F ', ' D '); $arr 3= array_intersect ($arr, $arr 1 , $arr 2);p Rint_r ($arr 3);//array ([0] = A)

Note: Array_intersect () considers them equal only if the two elements have the same data type.

To find the intersection of associative arrays

ARRAY_INTERSECT_ASSOC () is basically the same as Array_intersect (), except that it also considers the keys of the array in the comparison. Therefore, only key/value pairs that appear in the first array and in all other input arrays are returned to the result array. The form is as follows:

$arr = Array (' a ' = = ' A ', ' b ' = = ' B ', ' c ' = = ' C ', ' d ' = ' d '); $arr 1= Array (' a ' = ' = ' A ', ' c ' = = ' B ', ' E '); $arr 2 = Array (' a ' = = ' A ', ' b ' = ' F ', ' d ' = ' B '); $arr 3= Array_intersect_assoc ($arr, $arr 1, $arr 2);p Rint_r ($arr 3);// Array ([a] = a)

Finding the difference set of associative arrays

The function Array_diff_assoc () is basically the same as Array_diff (), except that it also considers the keys of the array at the time of comparison, so only the key/value pairs that appear in the first array and not in the other input arrays are returned to the result array. The form is as follows:

$arr = Array (' a ' = = ' A ', ' b ' = = ' B ', ' c ' = = ' C ', ' d ' = ' d '); $arr 1= Array (' a ' = ' = ' A ', ' b ' = ' = ' B ', ' e ' = ' e '); arr3= Array_diff_assoc ($arr, $arr 1);p Rint_r ($arr 3);//array ([c] = c [d] + D)

Other useful array functions

Returns a random set of keys

The Array_rand () function returns one or more keys in the array. The form is:

$arr = Array (' a ' = = ' A ', ' b ' = = ' B ', ' c ' = = ' C ', ' d ' = ' d '); $arr 1= Array_rand ($arr, 2);p Rint_r ($arr 1);//array ([0 ] = b [1] = + D)

Random Shuffle array elements

The shuffle () function randomly re-sorts the array elements.

Sum the values in an array

The Array_sum () function adds all the values in the array together, returning the final and form as follows:

$arr = Array (' A ', ' + ', ' B '); $count = Array_sum ($arr);p rint_r ($count);//44

If the array contains other data types (such as strings), the values are ignored.

Dividing an array

The Array_chunk () function decomposes an array into a multidimensional array that consists of multiple arrays containing size elements. The form is as follows:

$arr = Array (' A ', ' B ', ' C ', ' D '), $arr 1= array_chunk ($arr, 2);p Rint_r ($arr 1);//array ([0] = = Array ([0] = A [1] => ; B) [1] = = Array ([0] = C [1]=> D))

http://www.bkjia.com/PHPjc/1123803.html www.bkjia.com true http://www.bkjia.com/PHPjc/1123803.html techarticle learn PHP's array summary "experience", PHP array summary php has a lot of functions on the array, convenient array operation. Definition: Array Each entity contains two items: Key and value, can be ...

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