PHP array Getting Started Tutorial summary

Source: Internet
Author: User
I don't know how PHP beginners learn functions, but I think learning functions must be objective-driven. taking array functions as an example! How can we learn so many array functions? In fact, we only need to know what operations we need to perform on the array, and then classify these operations into general impressions. then, with your practice, you will be very clear about these functions. here, I would like to remind you that the manual should be retained! Not to mention, array functions are generally classified into the following categories (do not be afraid of English ):
Outputting arrays
Creating arrays
Testing for an array
Locating array elements
Traversing arrays
Determining array size and element uniqueness
Sorting arrays
Merging, slicing, splicing, and dissecting arrays


Outputting arrays
Print_r ()
If I am not familiar with this, I don't want to say more! The most basic function, of course, outputs an array but uses a loop structure for output. but why not use this convenient output function!

Creating arrays
Array ()
I don't want to talk about this function either. In fact, this function can only be regarded as a language structure. you have used it when creating arrays. if you have never used it, you can only say it, bro, I'm speechless!
List ()
This function is just a language structure like the array () mentioned above. it assigns values to a group of variables in one step!
For more information, see the manual!
Range ();
ArrayRange(Mixed low, mixed high [, number step])
Creates an array containing a specified range of units.
Example: $ arr = range (0, 6 );
Equivalent to $ arr = array (0, 1, 2, 3, 4, 5, 6 );
Generally, data is arranged from low to high. if low> high, data is arranged from high to low;

Testing for an array
Is_array ();
Test whether the variable is of the array type. If yes, true is returned. if not, false is returned. it is a basic and practical function!

Adding and removing array elements
Array_push ()
IntArray_push(Array & target_array, mixed var [, mixed...])
Add one or more cells to the array from the end! Returns the total number of cells in the new array!
Example:

Copy the PHP content to the clipboard. PHP code: $states =array( ‘Ohio' , ‘New York' );
array_push ( $states , ‘California' , ‘Texas' );
//output: array((‘Ohio',‘New York' , ‘California',‘Texas');

Array_pop ();
The last cell of the array is displayed and returned, and the length of the array is reduced by one. The array pointer is reset after use!
Example:

Copy the PHP content to the clipboard. PHP code: $states =array( ‘Ohio' , ‘New York' );
$state = array_pop ( $states );
//output: New York

Array_shift ();
It is similar to array_pop, except that it removes and returns the first value of the array. The number Key will record data from scratch, and the text key name will remain unchanged!

Array_unshift ();
Similar to array_push, data is inserted from the array header! The number Key will record data from scratch, and the text key name will remain unchanged!

Array_pad ();
ArrayArray_pad(Array input, intpad_size, mixed pad_value)
Fill the array with the specified length!
If pad_size is positive, it is filled from the right, negative, left, small, and array length! For examples, see the manual!

Locating array elements
In_array ();
Check whether a value exists in the array. For more information, see the manual!

Array_keys ();
ArrayArray_keys(Array input [, mixed search_value [, bool strict])
Returns all key names in the array. If search_value is selected, the selected key name is returned! From PHP 5], you can use the strict parameter for full comparison (= ).

Array_key_exists ();
BoolArray_key_exists(Mixed key, array search)
Check whether the given key name or index exists in the array. If yes, true is returned. For more specific applications, see the manual!

Array_values ();
ArrayArray_values(Array input)
Similar to array_keys! All key values of the array are returned!

Array_search ();
MixedArray_search(Mixed needle, array haystack [, bool strict])
Search for the needle parameter in haystack and return the key name if it is found. otherwiseFALSE.
If needle is a string, it is case sensitive!
If strict is true, the comparison type is required.
If needle appears more than once in haystack, the first matched Key is returned. To return keys of all matched values, replace array_keys () with the optional parameter search_value!


Traversing arrays

Key ();
MixedKey(Array & array)
Returns the key name of the current cell in the array!

Reset ();
Resets the pointer of an array.

Each ();
Returns the key/value pair of the current unit in the array, and moves the pointer one by one!

Current ();
Returns the value of the array unit pointed to by the internal pointer and does not move the pointer. If the end of the cell list is exceeded, false is returned.

End ();
Move the internal pointer of array to the last unit and return its value.

Next ();
Returns the value of the next unit pointed to by the internal pointer of the array, or if no more units exist.FALSE.

Prev ();
Returns the value of the previous unit pointed to by the internal pointer of the array, or if no more units exist.FALSE.

Array_walk ();
BoolArray_walk(Array & array, callback funcname [, mixed userdata])
For more information, see the manual!
Example:

Array_reverse ();
ArrayArray_reverse(Array [, bool preserve_keys])
Accept array as input and return a new array in reverse order. if preserve_keys isTRUEThe original key name is retained.
Example:

Copy the PHP content to the clipboard. PHP code: $states =array( ‘Delaware' , ‘Pennsylvania' , ‘New Jersey' );
print_r ( array_reverse ( $states ));
//Array ([0]=>New Jersey [1]=>Pennsylvania[2]=>Delaware)
$states = array( ‘Delaware' , ‘Pennsylvania' , ‘New Jersey' );
print_r ( array_reverse ( $states , 1 ));
//Array ([2]=>New Jersey [1]=>Pennsylvania[0]=>Delaware)

Array_flip ();
ArrayArray_flip(Array trans)
Exchange key/value pairs in the array. Note that the value in trans must be valid key names, for example, integer or string. If the value type is incorrect, a warning will be issued, and the problematic key/value pair will not be reversed.
If the same value appears multiple times, the last key name is used as its value, and all others are lost.
Example:

Copy the PHP content to the clipboard. PHP code: $trans =array( "a" => 1 , "b" => 1 , "c" => 2 );
$trans = array_flip ( $trans );
print_r ( $trans );
//Array([1]=>b[2]=>c );

Determining array size and element uniqueness

Count ();
Calculate the number of units in the array or the number of attributes in the object. this is very basic!

Array_count_values ();
Returns an array that uses the value in the input array as the key name and the number of times this value appears in the input array as the value.
Example:

Copy the PHP content to the clipboard. PHP code: $array= array( 1 , "hello" , 1 , "world" , "hello" );
print_r ( array_count_values ( $array ));

Array_unique ();
ArrayArray_unique(Array)
Accept array as input and return a new array without repeated values.
Example:

Copy the PHP content to the clipboard. PHP code: $input =array( "a" => "green" , "red" , "b" => "green" , "blue" , "red" );
$result = array_unique ( $input );
print_r ( $result );

For detailed usage, see the manual!

Sorting arrays

Sort ();
This function sorts arrays. When the function ends, the group unit will be rescheduled from the lowest to the highest.
Note:This function assigns a new key name to the unit in array. This will delete the original key name, not just the reorder.

Natsort ();
Sort arrays by natural sorting!
Example:

Copy the PHP content to the clipboard. PHP code: $array1 = $array2 = array( "img12.png" , "img10.png" , "img2.png" , "img1.png" );
sort ( $array1 );
echo "Standard sorting\n" ;
print_r ( $array1 );

natsort ( $array2 );
echo "\nNatural order sorting\n" ;
print_r ( $array2 );

Natcasesort ();
It is consistent with natsort (), except that it is case insensitive!

Rsort ();
It is consistent with sort (). This is reverse sorting.
Asort ();
And sort (), but keep the key name unchanged.
Array_multisort ();
Sort multiple arrays or multi-dimensional arrays. for details, refer to the manual!
Arsort ();
Similar to rsort (), but the key name remains unchanged.
Ksort ();
Similar to sort (), sort key names.
Krsort ();
Similar to ksort (), but reverse sorting.
Usort ();
Use a user-defined function to sort arrays!

Merging, slicing, splicing, and dissectingarrays

Array_combine ();
ArrayArray_combine(Array keys, array values)
Create an array with the value of one array as its key name and the value of another array as its value

Array_merge ();
ArrayArray_merge(Array array1 [, array array2 [, array...])
Combine the elements of one or more arrays. the values of an array are appended to the values of the previous array. Returns an array of results.
If the input array contains the same string key name, the value after the key name overwrites the previous value.
However, if the array contains a number key nameNoOverwrite the original value, but append it to the end.
Example:

Copy the PHP content to the clipboard. PHP code: $array1 =array( "color" => "red" , 2 , 4 );
$array2 = array( "a" , "b" , "color" => "green" , "shape" => "trapezoid" , 4 );
$result = array_merge ( $array1 , $array2 );
print_r ( $result );

If only one array is assigned and the array is indexed by number, the key name is re-indexed continuously.

Copy the PHP content to the clipboard. PHP code: $array1 = array();
$array2 = array( 1 => "data" );
$result = array_merge ( $array1 , $array2 );

If you want to completely retain the original array and only want to append the new array to the end, use the + operator:

Copy the PHP content to the clipboard. PHP code: $array1 = array();
$array2 = array( 1 => "data" );
$result = $array1 + $array2 ;

Array_merge_recursive ();
ArrayArray_merge_recursive(Arrayarray1 [, array...])
Combine the elements of one or more arrays. the values of an array are appended to the values of the previous array. Returns an array of results.
If the input array has the same string key name, these values will be merged into an array, which will be recursive. Therefore, if a value is an array, this function combines the corresponding entries into another array. However, if the array has the same array key name, the latter value will not overwrite the original value, but will be appended to the back.

Copy the PHP content to the clipboard. PHP code: $ar1 = array( "color" =>array( "favorite" => "red" ), 5 );
$ar2 = array( 10 , "color" => array( "favorite" => "green" , "blue" ));
$result = array_merge_recursive ( $ar1 , $ar2 );
print_r ( $result );

For more details, see the manual!

Array_slice ();
ArrayArray_slice(Array, effecffset [, int length [, bool preserve_keys])
Extract a segment from the array.
If offset is not negative, the sequence starts from this offset in array. If offset is negative, the sequence starts from the end of the array.
If length is given and is positive, the sequence will have so many units. If length is given and it is negative, the sequence is terminated so far from the end of the array. If this parameter is omitted, the sequence starts from offset to the end of array.
Example:

Copy the PHP content to the clipboard. PHP code: $input = array( "a" , "b" , "c" , "d" , "e" );
$output = array_slice ( $input , 2 ); // returns"c", "d", and "e"
$output = array_slice ( $input , - 2 , 1 ); // returns "d"
$output = array_slice ( $input , 0 , 3 ); // returns "a","b", and "c"
// note the differences in the array keys
print_r ( array_slice ( $input , 2 , - 1 ));
print_r ( array_slice ( $input , 2 , - 1 , true ));

Array_splice ();
ArrayArray_splice(Array & input, int offset [, int length [, array replacement])
Remove the units specified by offset and length from the input array. if The replacement parameter is provided, replacement is used. Returns an array containing the removed cells. Note that the number key name in input is not retained.
If offset is not negative, the sequence starts from this offset in array. If offset is negative, the sequence starts from the end of the array.
If length is given and is positive, the sequence will have so many units. If length is given and it is negative, the sequence is terminated so far from the end of the array. If this parameter is omitted, the sequence starts from offset to the end of array.
For more information, see the manual!

Array_intersect ();
ArrayArray_intersect(Arrayarray1, array array2 [, array...])
Returns an array containing all values that appear in the array of all other parameters in array1. Note that the key name remains unchanged.
Example:

Copy the PHP content to the clipboard. PHP code: $array1 =array( "a" => "green" , "red" , "blue" );
$array2 = array( "b" => "green" , "yellow" , "red" );
$result = array_intersect ( $array1 , $array2 );

Array_intersect_assoc ();
Note that, unlike array_intersect (), the key name is also used for comparison.

Array_diff ();
Similar to array_intersect (), it is only a difference set for calculating arrays.

Array_diff_assoc ();
Similar to array_intersect_assoc (), it is only a difference set for calculating arrays.

Other useful array functions

Array_rand ();
MixedArray_rand(Array input [, int num_req])
Randomly retrieve one or more units from the array.

Shuffle ();
BoolShuffle(Array & array)
This function breaks down an array (the order of random units.
This function assigns a new key name to the unit in array. This will delete the original key name, not just the reorder.

Array_sum ();
Returns the sum of all values in the array as an integer or floating-point number.

Array_chunk ();
ArrayArray_chunk(Array input, intsize [, bool preserve_keys])
Splits an array into multiple arrays. the number of units in each array is determined by the size. The number of units in the last array may be smaller. The obtained array is a unit in a multi-dimensional array, and its index starts from scratch.
Set the optional parameter preserve_keys to TRUE so that PHP retains the original key name in the input array. If you specify FALSE, each result array is indexed with a new number starting from scratch. The default value is FALSE.

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.