Examples of PHP array processing functions

Source: Internet
Author: User
Tags compact sorts

In PHP, the values stored in the array become array elements, the array has a one-dimensional array and a multidimensional array, and the index of each array element is also called the keyword, and access to the array elements can be indexed. Examples of array processing functions are:

I. Creating an array

1. Create an array using the array () function: array array ([$key =>] $value,...)

$key = = $value, defines the key name and value of the keyword, and the custom key name can be a string or a number. If the key name is omitted, the function automatically produces an integer starting from 0 as the key name. If the key name is not specified for a given value only, the key name takes the value after the largest integer key name +1 in front of the value.

Note: ① can use the Print_r () function to print an array. Print_r () function syntax: bool Print_r (mixed expression [, bool return]). If you want to capture the output of Print_r (), you can use the return function, which is set to True,print_r () will not print the result, but return its output;

② If the array defines two identical key names, the next one will overwrite the previous one;

③ to use a value in the array, you can use the form $array["key Name"];

④ can use the count () and sizeof () functions to get the number of array elements.

2. Creating an array with variables

The compact () function can set one or more variables, even arrays, to create an array of elements whose key names are variable names of variables, values of which are the values of the variables: array compact (mixed $varname [, mixed ...])

Each $varname can be a string that includes a variable name or an array that contains the variable name. For each parameter, the compact () looks for the variable name in the current symbol table and adds it to the output array, the variable name becomes the key name, and the contents of the variable become the value of the key, and any strings that have no variable name corresponding to it are ignored.

The extract () function converts a cell (key value) in an array into a variable.

3. Create an array using two arrays: Array_combin ()

Array Array_combin (array $key, array $values)

The Array_combin () function uses the value in the $key array as the key name, uses the value in the $values array as the corresponding value, and finally returns a new array.

4. Create an array of the specified range: range ()

Array range (mixed $low, mixed $high [, number $step])

$low the value of the starting element for the array, $high the value of the array end element. If the $low> $high, the sequence will be from $high to $low. $step is a stepping value between cells, $step should be positive and the default is 1. The range () function returns an array where the value of the array element is the value from $low to $high.

5. You can also set up an array automatically.

Two. Key-value operation

1. Check if there is a key name and value in the array can use the array_key_exists () and the In_array () function, both of which are Boolean, the presence returns True, and False if none exists.

The Isset () function can also be used to check the existence of a key name in an array, but if the value of the check key name corresponds to the Null,isset () function returns False, and Array_key_exists () returns True.

The 2.array_search () function can also be used to check for the existence of values in an array, return the value of the key if it exists, and return NULL if it does not exist.

The 3.key () function can get the key name of the current cell of the array

The next () function returns the value of the next cell in the array and moves the inner pointer in the array forward one bit, and if it is already at the end of the array, the return False,prev () function moves the inner pointer in the array backward one bit.

End ($array): Indicates that the inner pointer in the array points to the last cell;

Reset ($array): Indicates that the inner pointer in the array points to the first cell, which is a pointer to the reset array;

Each ($array): Represents the return of the current key name and value, and moves down one bit to the array pointer.

The 4.list () function assigns the values in the array to the variable you are making. The list () function assigns values to the corresponding variables in the function from the first value of the array, and if the number of variables is less than the number of elements in the array, only the elements of the array and the number of equal variables are assigned. The list () function can only be used for arrays of key names and assume that numeric key names start at 0, and if the key name is not a sequential number, an error is most likely to occur.

5. Use the Array_fill () and Array_fill_keys () functions to populate the values and key names of the array with the given values

Array array_fill (int $start _index,int $num, mixed $value)

The Array_fill () function uses the value of the parameter $value to populate an array with $num cells starting with the first $start_index cells. $num must be a value greater than 0, or PHP will issue a warning.

Array Array_fill_keys (array $keys, mixed $value)

The Array_fill_keys function uses the value in the given array $keys as the key name, $value as the value, and returns the new array.

The 6.ARRAY_FILP () function can exchange key names and values in an array.

The value in the array must be a valid key name to be able to be exchanged using the function, and if the same value is in the array before the interchange, the value remains the last one after the same value is converted to the key name.

7.array_keys () and array_values () can get all the key names and values in the array and save them in a new array.

The 8.array_splice () function can delete one or more cells in an array and replace them with other values

Array Array_splice (array $input, int $offset [, int $length [, array $replacement]])

The Array_splice () function removes the cells specified by $offset and $length in the $input array and, if the $replacement parameter is provided, replaces the removed unit with the value in $replacement. Finally, an array containing the removed cells is returned.

The $offset is the specified offset, and if $offset is positive, it is removed from the specified offset in the $input array. If $offset is negative, it is removed from the offset specified by the value of the countdown at the end of $input.

$length is the number of cells that are specified for deletion, and if $length is omitted, all parts from $offset to the end of the array are moved. If $length is specified and positive values are removed, the cells are $length after $offset, and if $length is specified and negative, all cells from $offset to the end of the array ending $length are removed. To remove all cells from $offset to the end of the array when $replacement is given, you can use COUNT ($input) as the $length.

If the $relpacement array is given, the removed cell is replaced by the cells in this array. If the combined result of the specified $offset and $length does not remove any values, the cells in the $replacement array are inserted into the $offset specified location. If the value used to replace has only one cell, then you do not need to add "array" to it, unless the cell itself is an array.

The 9.array_unique () function can move duplicate values in the array, return a new one, and not break the original array.

Three. Traversal and output of arrays

1. Using the while loop to access the array

A while loop, List () and each () function can be used to implement the traversal of the array. The function of the list () function is to assign the values in the array to variables, the function of each () function is to return the current health name and value, and move the array pointer down one bit.

2. Using a For loop to access an array

Using a For loop can only access an array of integer types whose key names are ordered.

3. Accessing an array using a Foreach Loop

A foreach loop is a loop that is designed to iterate through an array.

foreach (array_expression as $value)

Code snippet

foreach (array_expression as $key = $value)

Code snippet

The first format iterates through the given array of array_expression. In each loop, the value of the current cell is assigned to the variable $value and the pointer inside the array moves forward one step (the next loop will get the next cell). The second format does the same thing, but the key name of the current cell is also assigned to the variable $key in each loop.

Four. Sorting of arrays

1. Ascending

The ①sort () function can sort an already defined array so that the array cells are re-indexed from low to high in array values.

BOOL Sort (array $array [, int $sort _flags])

Returns true if the sort succeeds, otherwise false is returned. $array is the array to sort, $sort the value of _flags can affect the behavior of the sort, $sort _flags can fetch 4 values.

Sort_regular: Normal comparison unit, default

Sort_numeric: Units are compared as numbers

Sort_string: The unit is compared as a string

Sort_local_string: The unit is treated as a string comparison according to the current locale.

The sort () function not only sorts the array, but also removes the original key name and reassign the key name of the auto-index.

The ②asort () function can also sort the values of the array in ascending order, and the arrays that are sorted by using the Asort () function retain the association between the key name and the value.

The ③ksort () function is used to sort the key names of an array, and the association of key names and values does not change after sorting.

2. Reverse

Descending sorting can use the Rsort (), Arsort (), Krsort () functions.

The Rsort () function sorts the values in the array in descending order and modifies the array key names to one-dimensional numeric key names; the Arsort () function sorts the values in the array in descending order without changing the association between the key names and values; the Krsort () function sorts the key names in the array in descending order.

3. Sorting multidimensional arrays

The Array_multisort () function can sort multiple arrays at once, or sort multidimensional arrays based on one-dimensional or multidimensional arrays.

BOOL Array_multisort (array $ar 1[,mixed $arg [, Mixed $ ... [, Array $ ...]])

The first argument must be an array, and each subsequent argument can be an array or a sort flag listed below.

Sort order Flags:

SORT_ASC: Default value, sorted in ascending order

Sort_desc: Sort in descending order

Sort Type flag:

Sort_regular: Default value, Comparison by usual method

Sort_numeric: By numerical comparison

Sort_string: Comparing by string

After each array, you cannot make two of the same sort flags, and the sort flags that are made after each array are only valid for that array.

Sorting using the Array_multisort () function is the string key name remains the same, but the numeric key name is re-indexed. When a function's argument is an array list, the function first sorts the first array in the list in ascending order, and the order of the values in the next array is arranged in the sequence of the values of the corresponding first array.

The array elements of all arrays in the array list must be equal, otherwise a warning is issued when using the Array_multisort () function.

4. Reordering arrays

The shuffle () function is to arrange the array in random order and delete the original key name to establish an automatic index.

The Array_reverse () function sorts an array of cells in reverse order: Array array_reverse (array $array [, BOOL $preserve _keys]) if $preserve_ The value of keys is true to retain the original key name, or false to re-index the array.

5. Natural sorting

The Natsort () function implements a sort algorithm that is similar to how people usually sort letters, arrays, and strings, and maintains the association of the original key/value. Called "Natural sort". The Natsort () function is case-sensitive, and the Natcasesort () function is also a natural sort function, but not case-sensitive

Five. Other

1. Merging arrays

The Array_merge () function can merge one or more arrays, and the values in an array Fujian precedes the previous array, returning an array as the result.

Array Array_merge (array $array 1[,array $array 2[,array $ ...])

If the input array has the same string key name, the value following the key name overrides the previous value. If the array contains an array key name, subsequent values will not overwrite the original value, but are appended to the back. If only one array is given and the array is a numeric index, the key name is re-indexed in a sequential manner.

When a multidimensional array is merged, the Array_merge () function returns the array after one dimension as a unit. Use the array_merge_recusive () function to merge an array in the case of keeping the existing arrays structure.

2. Stack operation of arrays

A stack is a structure that stores data, characterized by "LIFO".

The stack operation actually removes the last element of the array, using the Array_pop () function;

The stack operation is to add the new cell to the end of the array, using the Array_push () function, with the following syntax:

int Array_push (array $array, mixed $var [, mixed $ ...]

The Array_push () function treats the array $array as a stack and adds the incoming variable $var to the end of the $array, and the length of the $array increases depending on the number of variables that are in the stack.

3. Get the current cell of the array

The current () function is able to get the value of the cell that the pointer points to in the array, but does not move the inner pointer of the array.

4. Array calculations

Use the count (), sizeof () function to calculate the number of elements in an array, but instead use the array_count_values () function to calculate the number of occurrences of a value in the array. Syntax format:

Array array_count_values (array $input)

The Array_count_values () function returns an array that uses the value in the $input array as the key name, the number of occurrences in the $input array as the value.

This article is from the "Rangers" blog, please be sure to keep this source http://ccnupxz.blog.51cto.com/8803964/1834265

Examples of PHP array processing functions

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.