PHP Array Basics Summary and sorting

Source: Internet
Author: User
Tags array definition shuffle sorts

Recently just internship, often used in the array of PHP, so summarize, not at any time to random search.

First: basic knowledge

PHP supports numeric indexed arrays and associative arrays, and associative arrays allow more meaningful data, such as strings, to be indexed. And an index that allows you to use arrays and strings as arrays in an interval.
1. Array definition:

$arr = [1,2,3,4]; // the digital Index array   php5.4 The new method provided above $arr = [' A ' =>1, ' B ' =>2]; // Associative index Array $arr Array (1,2,3,4); $arr Array (' A ' =>1, ' B ' =>2); $arr Range (1,n); // automatically create 1~n array of numbers

The PHP array does not need to be pre-initialized or created, and is automatically created when it is first used, such as:

$arr [' a '] = 1; $arr [' b '] = 2; $arr [' C '] = 3;

2. Array traversal

  1. For loop
    Can only be used in an ordered array of numeric indices

     for ($i = 0; $i<count($arr); $i++echo  $arr[$i];}

  2. Foreach

     for ($arras $keyand$valueecho$key. " --". $value ;}

  3. each

     while ($eleeach ($arrecho ele[' key '). " --". ele[' value ');}

  4. List (common)

    Reset ($arr); // Reset pointer  while (list($key,$valueeach ($arr)) {echo   $key. " --". $value ;}

3, two-dimensional or multidimensional arrays

$arr Array (    ' a ' = =array()    ;' b ' = =array();    );

4, array definition needs attention (from PHP manual)

Key will have the following casts:
1. A string containing a valid integer value is converted to an integral type. For example, the key name "8" will actually be stored as 8. However, "08" does not cast because it is not a valid decimal value.
2, the floating-point number will be converted to integer, meaning that its fractional part will be abandoned. For example, key name 8.7 will actually be stored as 8.
3, the Boolean value will also be converted to integral type. That is, the key name true is actually stored as 1 and the key name false is stored as 0.
4, NULL is converted to an empty string, that is, the key name null is actually stored as "".
5. Arrays and objects cannot be used as key names. Insisting on doing so will result in a warning: illegal offset type.
6. If more than one cell in the array definition uses the same key name, only the last one is used, and the previous is overwritten.

$array Array (    1    = "A",    "1"  = "B",    1.5  = "C",    true = "D",); Var_dump ($array); // Results Array (1) {  [1]=>  string(1) "D"}
Two: Sorting of arrays

Sorting is the most frequently used operation in an array operation. PHP provides a number of sorting functions.

One: Sort function of a dimension array

1, sort (): The one-dimensional array can be sorted in ascending order, if it is a number, then from small to large row, if it is a string, then the first letter table row
2, Asort (): The ascending value of the associative array
3, Ksort (): The ascending of key for associative array
The inverse order function corresponding to the above three functions is Rsort (), Arsort (), Krsort (); in descending order
4, Array_reverse (): Reverse the array
5. Shuffle (): Randomly sort the elements of the array

Second: Sorting of multidimensional arrays

Using functions such as sort (), Ksort (), you can make keywords for one-dimensional arrays, by value, and reverse sort, but these functions cannot be used in multidimensional arrays. You will need to use a user-defined sort function at this point.
PHP provides Usort (), Uasort (), Uksort (), functions to sort two-dimensional arrays, which require us to define a sort function and pass it on to it. The custom function needs to accept two parameters and return which parameter should be preceded (by default in ascending order): false or negative, the first argument is preceded by a true or positive number, and the second argument is preceded by an equal of 0. If you want to reverse the order, the execution returns a value Exchange

//Code Testing$arr=Array(    Array(' Key1 ' =>900, ' key2 ' = ' bash1 '),Array(' Key1 ' =>800, ' key2 ' = ' heh2 '),Array(' Key1 ' =>950, ' key2 ' = ' gosh4 '),);Var_dump($arr);functionAsc_number_sort ($x,$y){    if($x[' Key1 ']>$y[' Key1 ']){        return true; }Else if($x[' Key1 ']=$y[' Key1 ']){        return false; }Else{        return0; }}Usort($arr, ' Asc_number_sort ');Var_dump($arr);//Test ResultsArray(size=3)  0 =Array(size=2)      ' Key1 ' = int ' Key2 'string' Bash1 ' (length=5)  1 =Array(size=2)      ' Key1 ' = int ' Key2 'string' Heh2 ' (length=4)  2 =Array(size=2)      ' Key1 ' = int 950 ' Key2 ' =string' Gosh4 ' (length=5)Array(size=3)  0 =Array(size=2)      ' Key1 ' = int ' Key2 'string' Heh2 ' (length=4)  1 =Array(size=2)      ' Key1 ' = int ' Key2 'string' Bash1 ' (length=5)  2 =Array(size=2)      ' Key1 ' = int 950 ' Key2 ' =string' Gosh4 ' (length=5)
      PHP will continuously send an array of inner layers to this function to sort
    The
        usort () function sorts by numeric value, but it does not save the keywords for the outer array

      If we change the array to:
$arr=Array(    ' XC ' =Array(' key1 ' = ', ' key2 ' = ' bash1 '), ' as ' =Array(' key1 ' = ' + ', ' key2 ' = ' heh2 '), ' dw ' =Array(' key1 ' = 950, ' key2 ' = ' gosh4 '),) test results are:Array(size=3)  0 =Array(size=2)      ' Key1 ' = int ' Key2 'string' Heh2 ' (length=4)  1 =Array(size=2)      ' Key1 ' = int ' Key2 'string' Bash1 ' (length=5)  2 =Array(size=2)      ' Key1 ' = int 950 ' Key2 ' =string' Gosh4 ' (length=5)

Can find the outermost array of the keyword ' xc ', ' as ', ' DW ' not saved
Use the Uasort () function to save keywords

 uasort  ( $arr , ' Asc_number_sort ') Span style= "color: #000000;" >); array  (Size=3 ' as ' = array  (Size=2)  ' key1 ' = ' + int ' key2 ' and string  ' heh2 ' (Length=4)  ' xc ' = array  (Size=2 ' K Ey1 ' = = Int ' Key2 ' + string  ' bash1 ' (Length=5)  ' dw ' = array  (Size=2)  ' K Ey1 ' = = int 950 ' key2 ' + string  ' Gosh4 ' (length=5) 
      when the Uksort () function is used, the sort is based on the keyword
Three: Some problems encountered in actual use

1. The JSON array and the PHP array appear to be very similar, actually not the same, need to use
Json_decode () function converts JSON to PHP array (requires attention to coding issues)
2, in the array if you need to make judgments, you need to let the judgment jump ahead of time, do not write large pieces of logic in the IF.
3, array values: Array from small to large, to take the largest n values should be taken from the back
$arr. Slice (-N);

PHP array functions

Array () to create arrays.
Array_change_key_case () Changes all the keys in the array to lowercase or uppercase.
Array_chunk () splits an array into a new array block.
Array_column () returns the value of a single column in the input array.
Array_combine () Creates a new array by merging two arrays.
Array_count_values () is used to count the occurrences of all values in the array.
Array_diff () compares the array and returns the difference set (only the key value is compared).
ARRAY_DIFF_ASSOC () compares the array, returning the difference (comparing key names and key values).
Array_diff_key () compares the array, returning the difference set (only the key name is compared).
ARRAY_DIFF_UASSOC () compares the array, returns the difference set (comparison key name and key value, using the user-defined key name comparison function).
Array_diff_ukey () compares the array, returns the difference set (only the key name is compared, using the user-defined key name comparison function).
Array_fill () fills the array with the given key value.
Array_fill_keys () fills the array with the given key value for the specified key name.
Array_filter () filters the elements in the array with a callback function. Remove null values from the array by default
Array_flip () Swaps the keys and values in the array.
Array_intersect () compares the array, returning the intersection (only the key values are compared).
ARRAY_INTERSECT_ASSOC () compares the array, returning the intersection (comparing key names and key values).
Array_intersect_key () compares the array, returning the intersection (only the key name is compared).
ARRAY_INTERSECT_UASSOC () compares the array, returning the intersection (comparing key names and key values, using a user-defined key-name comparison function).
Array_intersect_ukey () compares the array, returning the intersection (only the key names are compared, using the user-defined key-name comparison function).
Array_key_exists () checks whether the specified key name exists in the array.
Array_keys () returns all the key names in the array.
Array_map () sends each value in the array to the user-defined function, returning the new value.
Array_merge () merges one or more arrays into an array.
Array_merge_recursive () recursively merges one or more arrays.
Array_multisort () sorts multiple arrays or multidimensional arrays.
Array_pad () fills the array to the specified length with a value.
Array_pop () deletes the last element of the array (out of the stack).
Array_product () computes the product of all the values in the array.
Array_push () inserts one or more elements into the end of the array (into the stack).
Array_rand () returns one or more random keys in the array.
Array_reduce () returns an array as a string by using a user-defined function.
Array_replace () replaces the value of the first array with the value of the subsequent array.
Array_replace_recursive () recursively replaces the value of the first array with the value of the subsequent array.
Array_reverse () returns the array in reverse order.
Array_search () Searches for the given value in the array and returns the key name.
Array_shift () deletes the first element in the array and returns the value of the deleted element.
Array_slice () returns the selected part of the array.
Array_splice () deletes and replaces the specified element in the array.
Array_sum () returns the and of the values in the array.
Array_udiff () compares the array, returns the difference set (compares values only, using a user-defined key-name comparison function).
ARRAY_UDIFF_ASSOC () compares the array, returns the difference (comparison key and value, uses the built-in function to compare the key name, and uses the user-defined function to compare the key value).
ARRAY_UDIFF_UASSOC () compares arrays, returns the difference set (comparison keys and values, using two user-defined key-name comparison functions).
Array_uintersect () compares the array, returning the intersection (comparing values only, using a user-defined key-name comparison function).
ARRAY_UINTERSECT_ASSOC () compares the array, returns the intersection (comparison key and value, uses the built-in function to compare the key name, compares the key value using the user-defined function).
ARRAY_UINTERSECT_UASSOC () compares the array, returning the intersection (comparing keys and values, using two user-defined key-name comparison functions).
Array_unique () deletes duplicate values in the array.
Array_unshift () inserts one or more elements at the beginning of the array.
Array_values () returns all the values in the array.
Array_walk () applies a user function to each member in the array.
Array_walk_recursive () applies the user function recursively to each member in the array.
Arsort () Sorts the associative array in descending order of the key values.
Asort () Sorts the associative array in ascending order of key values.
The compact () creates an array that contains the variable names and their values.
COUNT () returns the number of elements in the array.
Current () returns the element in the array.
Each () returns the current key/value pair in the array.
End () points the inner pointer of the array to the last element.
Extract () Imports variables from the array into the current symbol table.
In_array () checks whether the specified value exists in the array.
Key () Gets the key name from the associative array.
The Krsort () array is reversed by key name.
Ksort () The array is sorted by key name.
List () assigns the values in the array to some variables.
Natcasesort () uses the "natural sort" algorithm to sort an array of case-insensitive letters.
Natsort () sorts the array with the "natural sort" algorithm.
Next () Moves the inner pointer in the array forward one bit.
The alias of the POS () current ().
Prev () returns the internal pointer of the array back to one bit.
Range () creates an array that contains the specified range of cells.
Reset () points the inner pointer of the array to the first element.
Rsort () Reverses the order of the arrays.
Shuffle () disrupts the array.
The alias of sizeof () count ().
Sort () sorts the array.
Uasort () Sorts the key values in the array using a user-defined comparison function.
Uksort () Sorts the key names in the array using a user-defined comparison function.
Usort () sorts the array using a user-defined comparison function.

PHP Array Basics Summary and sorting

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.