Learn PHP's array summary "experience" _php tips

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

PHP has a lot of functions about arrays to facilitate array manipulation.

Defined:

Each entity of an array contains two items: key and value, which can be retrieved by a query key. These keys can be numeric (numerical) or associated (associative) keys. Numeric keys have no real connection to values, they are just the positions of the values in the array.

PHP provides a lot of ways to traverse an array, not using association keys or numeric keys, depending on an attribute 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 you do not need to declare it before using an array. Although there is no limit, PHP still provides a formal and informal array declaration method.

References each element of the PHP array, indicated by a pair of brackets. Arrays do not have size limits, so you can create arrays by simply establishing a reference, for example:

$state [0]= ';

$state [1]= ' 222];

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

$state [] = ' a ';

$state [] = ' 222 ';

You can use array () to create arrays, such as:

$state =array (' A ', ' 222 ');

$state =array (' One ' => ', ' two ' => ' 222 ');

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

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

List ($one, $two, $three) = $state;

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

Fills an array with a predefined range of values, 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 over each array key and output the corresponding value.

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 when it succeeds, or false.

Test array

The Is_array () function is used to know whether a particular variable is an array.

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

Adding and removing array elements

PHP provides a number of functions for expanding and shrinking arrays, facilitating the emulation of various queue implementations.

To add an element to the array header:

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

$state = Array (' One ', ' all ', ') ';

Array_unshift ($state, ' a ');

$state = Array (' 00 ', ' 11 ', ' 22 ', ' 33 ');

To add an element to the end of an array:

The Array_push () function adds a value to the end of the array and returns the total number of elements in the array after adding a new value. By passing this variable as an input parameter to this function, the array is pressed into several 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 that uses 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 ');

To locate an array element

Search Arrays:

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

$user = Array (' n ', ' 222 ', ' 333 ');

$str = ' a ';

if (In_array ($str, $user)) {

echo ' yes ';

} else{

echo ' no ';

}

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

To search for an associative array:

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

$arr = Array (' One ' => ' 1 ', ' two ' => ' 2 ', ' Three ' => ' 3 ');

if (array_key_exists (' two ', $arr)) {

echo ' yes ';

} else{

echo ' no ';

}

To search for an associative array:

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

$arr = Array (' One ' => ' 1 ', ' two ' => ' 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 form of the following:

$arr = Array (' One ' => ' 1 ', ' two ' => ' 2 ', ' Three ' => ' 3 ');

$keys = Array_keys ($arr);

Var_dump ($keys);

Array (3) {[0]=> string (3) "One" [1]=> string (3) "Two" [2]=>string (5) "three"}

Get Array Value:

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

$arr = Array (' One ' => ' 1 ', ' two ' => ' 2 ', ' Three ' => ' 3 ');

$values = Array_values ($arr);

Var_dump ($values);

Array (3) {[0]=> string (1) "1" [1]=> string (1) "2" [2]=>string (1) "3"}

Traversing an array

Often you need to traverse the array and get each key or value (or both), and PHP provides some functions to meet the requirements. Many functions can accomplish two tasks, not only to get the key or the value of the current pointer position, but also to move the pointer down to 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 ', ' two ' => ' 2 ', ' Three ' => ' 3 ');

$key = key ($arr);

Var_dump ($key);

String (3) "One"

Note: The pointer is not moved each time the key () is invoked.

Gets the current array value:

The current () function returns the value of the array in the array at which the pointer is currently positioned. The form is as follows:

$arr = Array (' One ' => ' 1 ', ' two ' => ' 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 in a position as follows:

$arr =array (' One ' => ' 1 ', ' two ' => ' 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 the key 1 and value contain the corresponding data. Returns False if the previous pointer at the end of the array executes each ().

To move an array pointer:

1 Move the pointer to the next array position

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

$arr = Array (' One ' => ' 1 ', ' two ' => ' 2 ', ' Three ' => ' 3 ');

Echo Next ($arr); Output 2

echo next ($arr);//Output 3

2 Move the pointer to the previous array position

The prev () function returns the array value at a position before 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 process an array more than once in a script, you often use this function, and this function is often used at the end of the sort.

4 Move the pointer to the last array position

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

To pass an array value to a function:

The Array_walk () function passes each element in the array to the user-defined function. This function works 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 ', ' two ' => ' 2 ', ' Three ' => ' 3 ');

Array_walk ($arr, ' test ');

1 One

//2 two

//3 three

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

Determining array size and element uniqueness

To determine the size of an array:

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

If the optional Mode argument is started (set to 1), the array will perform a recursive count statistic element. Count (Array (), 1);

Note: the sizeof () function is an alias for Count (). functionality is consistent.

To count how often an array element appears:

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

Print_r ($res);

Array ([A] => 2 [B] => 1 [C] => 1)

The value represents the frequency of the occurrence.

To determine a unique array element:

The Array_unique () function deletes all duplicate values in the array, and returns an array of unique values in the form of the following:

$arr = Array (' A ', ' B ', ' C ', ' a ');

$res = Array_unique ($arr);

Print_r ($res);

Array ([0] => A [1] => B [2] => C)

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 by the localized environment (sort_locale_string).

Array sorting

Reverse array element Ordering:

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

$arr = Array (' A ', ' B ', ' C ');

$res = Array_reverse ($arr);

Print_r ($res);

Array ([0] => C [1] => B [2] => A)

If the optional parameter Preserve_keys is set to true, the key mapping is persisted, otherwise the rearranged values correspond to the corresponding keys at the previous position.

$arr = Array (' A ', ' B ', ' C ');

$res = Array_reverse ($arr, true);

Print_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);

Print_r ($res);

Array ([A] => 0 [B] => 1 [C] => 2)

Array Ordering:

The sort () function is sorted by array, and the elements are arranged in the order of the values from low to high, in the form of:

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

1) sort_numeric, sorted by numerical value. It is useful to sort integers and floating-point numbers.

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

3) sort_string, sort the elements in a correct order that is close to the human cognition.

The Asort () function is required to keep 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 retains the key/value association in the form as follows:

$arr = Array (' C ', ' B ', ' A ');

$res = $arr;

Print_r ($arr);

Sort ($arr);

Print_r ($arr);

Asort ($res);

Print_r ($res);

Array ([0]=> C [1] => B [2] => a) array ([0] => a [1] => B [2] => C) Array ([2] => a [1] => B [0] => C)

Sort the 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 exact sort behavior is determined by this value.

Sort the array in reverse order under the condition of keeping the key/value pair

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

$arr = Array (' C ', ' B ', ' A ', ' D ');

Arsort ($arr);

Print_r ($arr);

Array ([3] => D [0] => C [1] => B [2] => A)

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

Array Natural Sort

The Natsort () function provides a sort mechanism that is equivalent to what people normally 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

Natural sorting without case sensitivity

Such as:

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

Key values are sorted by array

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

Sort by array keys in reverse order

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

Sort by user custom rule

The Usort () function provides an alternative way to sort by using the user-defined comparison algorithm specified in the function. If you need to sort the data in some way, and any of the built-in sort functions in PHP do not provide the appropriate support, you need that function.

Array merging, splitting, joining, and decomposing

Merging arrays

The Array_merge () function merges the arrays together, returning a federated array. The resulting array begins with the first input array parameter, appended in the order in which the following array parameters appear. 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);

Print_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 (), and you can combine two or more arrays together to form a federated array. 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, replacing it with a 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. In the form of:

$arr = Array (' One ' => ' C ', ' One ' => ' B ');

$arr 1= Array (' Three ' => ' 1 ', ' One ' => ' 2 ');

$arr 2= array_merge_recursive ($arr, $arr 1);

Print_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);

Print_r ($arr 2);

Array ([A] => 1 [B] => 2)

Split Fraction Group

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

When offset is positive, the split begins at the offset position at 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 will start at offset until the last element of the array. If length is given and is positive, it ends at the offset+length position from the beginning of the array. Conversely, if length is given and is negative, the count (array)-|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);

Print_r ($arr 1);

Array ([0] => C)

To find the intersection of an array

The Array_intersect () function returns an array of reserved keys that consist of only 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);

Print_r ($arr 3);

Array ([0] => A)

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

To find the intersection of an associative array

ARRAY_INTERSECT_ASSOC () is essentially the same as Array_intersect (), except that it also considers the key 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);

Print_r ($arr 3);

Array ([a] => a)

To find the difference set of an associative array

The function Array_diff_assoc () is essentially the same as the Array_diff (), except that it also takes into account the key of the array when it is compared, so that key/value pairs appearing only in the first array and not in 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 ');

$arr 3= Array_diff_assoc ($arr, $arr 1);

Print_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. In the form of:

$arr = Array (' A ' => ' a ', ' B ' => ' B ', ' C ' => ' C ', ' d ' => ' d ');

$arr 1= Array_rand ($arr, 2);

Print_r ($arr 1);

Array ([0] => b [1] => D)

Random Shuffle array element

The shuffle () function randomly reorder the array elements.

Sum the values in the array

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

$arr = Array (' A ', +, ' B ');

$count = Array_sum ($arr);

Print_r ($count);

44

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

Dividing arrays

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

$arr = Array (' A ', ' B ', ' C ', ' D ');

$arr 1= Array_chunk ($arr, 2);

Print_r ($arr 1);

Array ([0] => Array ([0] => A [1] => B) [1] => Array ([0] => C [1]=> D))

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.