Some php array study notes _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Some php array learning notes. There are three types of php arrays: a numeric array with a numeric ID key, and an ID key in an array associated with a value multi-dimensional array containing one or more arrays, there are three types of php arrays: a numeric array with a numeric ID key, and an ID key in an array associated with a value multi-dimensional array containing one or more arrays, now let's look at my notes.
The code is as follows:

Header ('content-Type: text/html; charset = utf-8 ');
Echo'

';
Function var_array ($ array)
{
Echo'
'; 
var_dump($array);
echo '
';
}
Function printr ($ array)
{
Echo'
'; 
print_r($array);
echo '
';
}
Function getArr ($ sNum, $ eNum = 1, $ step = 1)
{
$ Arr = range ($ sNum, $ eNum, $ step );
$ ReArr = array ();
Foreach ($ arr as $ v)
{
$ ReArr [$ v] = rand (0, 10 );
}
Unset ($ arr );
Return $ reArr;
}
/**
* Array exercises
*/
//---------------------------------------------
// Array_change_key_case () changes the upper and lower case letters of the array index, which is determined by the last parameter: CASE_UPPER (converted to uppercase), CASE_LOWER (converted to lowercase by default)
$ ExpArr = array (
'First' => '1 ',
'Second' => '2 ',
'Third' => array (
'Huima '=> '3 ',
'Engzhuanm' => '5 ',
)
);
Printr (array_change_key_case ($ expArr); // converts all data to lowercase letters.
Printr (array_change_key_case ($ expArr ['third'], CASE_UPPER); // converts all data to uppercase and only converts a certain index key in the $ expArr array.
// Conclusion: This function only affects the layer of the array. Does not affect the original array.
Echo'

';
//---------------------------------------------
// Array_chunk ($ array, $ size, false)
// Splits an array into a multi-dimensional array. size determines that each $ size array is a multi-dimensional array. true/false determines whether the key value of the new array follows the key of the original array.
$ ExpArr = array ('4', '2', '6', 'D', '2 ');
Printr (array_chunk ($ expArr, 3 ));
// Conclusion: This function only affects the layer of the array. Does not affect the original array.
Echo'

';
//---------------------------------------------
// Array_combine ($ keyArr, $ valArr)
// Combine the two arrays into an array. $ keyArr serves as the key and $ valArr serves as the value.
$ ExpKey = array ('G', 'D', 'T ');
$ ExpVal = array ('5', '8', '7 ');
Printr (array_combine ($ expKey, $ expVal ));
// This function only affects the array layer and returns a new array.
Echo'

';
//---------------------------------------------
// Array_count_values ($ array)
// Count the number of occurrences of each value in the $ array, and use its value as the key of the new array, and the number of occurrences as the value
$ Array = array ('v1 '=> '000000', 'V2' => '000000', 'v3' => '20140901 ', 'V4 '=> '123', 'v5' => '123 ');
Printr (array_count_values ($ array ));
// Conclusion: This function can only be used to count values of the string and integer types. Other types will issue a warning!
Echo'

';
//---------------------------------------------
// Array_diff ($ array1, $ array2 ...)
// Array based on $ array1. its value does not appear in any other parameter array to form a new array.
$ Arr1 = array ('V4 '=> 458, 'gren', 'b5', 'a5 ');
$ Arr2 = array ('V4 '=> 598, 'red', 'a5', 'C4 ');
Printr (array_diff ($ arr1, $ arr2 ));
// Conclusion: use an array to locate the values that are not in the array. Statistics and Data comparison should be used.
// Array_intersect ($ array, $ parArr ,....)
// This function is similar to array_diff in function, except that array_intersect () returns a total of data, and array_diff only exists in $ array.
//
Echo'

';
//---------------------------------------------
// Array_diff_assoc ($ array1, $ array2 ...)
// Same as the array_diff () function, but the key is also used for comparison.
//
Echo'

';
//---------------------------------------------
// Array_diff_key
// Same as the array_diff () function
// Only the $ array1 key is used for searching with other parameter arrays.
//
Echo'

';
//---------------------------------------------
// Array_diff_uassoc ($ arr1, $ parArr..., callback function)
// Functions are the same as those of array_diff (), but you need to define a callback function.
// The role of the function is unknown.
//
Echo'

';
//---------------------------------------------
// Array_diff_ukey ($ arr1, $ parArr..., callback function)
// The function is the same as that of array_diff_key (), except that the callback function is the same as that of array_diff_uassoc.
//
//
Echo'

';
//---------------------------------------------
// Array_fill ($ startInt, $ numInt, $ value)
// Fill $ value in a new array. the starting position of the index of the new array is determined by $ startInt, and $ numInt controls the number of indexes generated by the array.
// Tip: Except $ value, $ startInt, and $ numInt must be digits. Otherwise, an error is returned.
Printr (array_fill (2, 5, 'value '));
// Conclusion: I did not expect any help
Echo'

';
//---------------------------------------------
// Array_fill_keys ($ arrKeys, $ value );
// The function is the same as the array_fill () function. Here, $ arrKeys [the value of an array] is used as the key for the new array.
$ ArrKeys = array ('45', 'D', 'B', 'C ');
Printr (array_fill_keys ($ arrKeys, 'value '));
Echo'

';
//---------------------------------------------
// Array_filter ($ arr, callBack function)
// Filter function. it determines the value of the $ arr array. if the callBack function returns true, the current key and value are added to the new array.
// TIP: the callback function can write a rule to filter out the array keys that do not comply with the rule.
Function cb ($ val)
{
Return $ val % 2 = 0;
}
$ Array = array ('k1 '=> 3, 'K2' => 5, 'k4' => 54654, 'k5 '=> 8794,894 5, 32549564 );
Printr ($ array, 'cb ');
// Tip: it is recommended that the callback function name be enclosed by quotation marks.
// Conclusion: this method can be used for data filtering integration.
Unset ($ array );
Echo'

';
//---------------------------------------------
// Array_flip ($ array)
// Convert the relationship between key and value in the array. Only Keys of the string and integr types are supported. if the keys of other types are not converted, a warning is triggered. In the generated new array, if the keys are the same, the existing key values will be replaced continuously.
$ Arr = array ('k1 '=> 'v1', 'K2' => 'V2', 'k3 '=> 'V4 ', 'k4 '=> 'V4', 'k5 '=> 'v5 ');
Printr (array_flip ($ arr ));
Unset ($ arr );
Echo'

';
//---------------------------------------------
// Array_key_exists ($ key, $ array)
// Determine whether a key exists in the current array and return bool. It can also be used to determine objects.
$ Array = array ('cb '=> 234, 'dv' => 45, 'one' => 897 );
If (array_key_exists ('one', $ array ))
Echo 'exist in this array ';
Else
Echo 'Nonexistent ';
Echo'

';
//---------------------------------------------
// Array_keys ($ array, $ selSearch_value)
// Return the key name in the array and form a new array. if $ selSearch_value is specified, the key name equal to $ selSearch_value in the array will be returned.
$ Array = getArr (4, 10 );
Printr (array_keys ($ array ));
Printr (array_keys ($ array, '5'); // value-based search
Unset ($ array );
// Conclusion: this can also be used for data statistics and data comparison and verification.
Echo'

';
//---------------------------------------------
Echo 'Array _ map :';
// Array_map ('callback', $ array ,...)
// Return the returned value of the callback function.
// The callback function can return an array. In addition, the callback function only accepts values in an array.
Function mapCb ($ n)
{
Return $ n * $ n;
}
$ Array = getArr (4, 15 );
Printr (array_map ('mapcb ', $ array ));
Echo'

';
//---------------------------------------------
// Array_merge ($ array, $ array2 ...)
// Combine multiple arrays into an array and rewrite the numeric index.
$ Arr1 = getArr (1, 5 );
$ Arr2 = getArr (5, 10 );
Printr (array_merge ($ arr1, $ arr2 ));
// Conclusion: multiple arrays form a new array.
Echo'

';
//---------------------------------------------
// Array_merge_recursive ($ arr1, $ arr2 ....)
// Functions are the same as above. But the function will make up a new array with the same key name, instead of replacing
// If necessary, use it based on the actual situation
Echo'

';
//---------------------------------------------
// Array_multisort ()
// Multi-dimensional array sorting. Currently, only two-dimensional array sorting is implemented. 3D estimation cannot be arranged
// This function directly changes the member array order
Echo'

';
//---------------------------------------------
// Array_pad ($ arr, $ size, $ value)
// Fill the array. if the current length of $ arr is less than $ size, $ value is used to fill the $ arr array until the length of $ arr is equal to $ size.
// If the length of $ arr is greater than or equal to $ size, this function will not fill $ arr. If $ size is less than 0, it is filled on the left side of $ arr, and if size is greater than 0, it is on the right side.
Echo'

';
//---------------------------------------------
// Array_pop ($ array)
// Remove the last key of the array.
Echo'

';
//---------------------------------------------
// Array_product ($ arr)
// Returns the product of all values in an array.
// Tip: This function cannot process non-numeric data. If the input array contains a string such as 'a and B ', php will report an error.
$ Arr = array (4, 5, 5 );
Echo array_product ($ arr );
Echo'

';
//---------------------------------------------
// Array_push ($ arr, $ keyArr)
// Add $ keyArr to the end of the $ arr array and add it as a key/stack.
// The difference between the two functions: array_merge () and array_merge_recursive:
// Arrap_push () is to add a $ keyArr to $ arr, while the other two functions connect multiple functions into one function.
Echo'

';
//---------------------------------------------
// Array_rand ($ arr, $ num = 1)
// Retrieve the keys in the current array. the number of keys in the array is determined by $ num. the default value is 1.
// If $ num is 1, it returns a string
// If $ num> 1 & $ num // Otherwise, php reports an error
$ Arr = getArr (5, 15 );
Printr (array_rand ($ arr, 4 ));
Echo'

';
//---------------------------------------------
// Array_reduce ()
// Similar to array_map (), the callback function is used to process the values in the logarithm group and accept the returned values.
// This function returns a string. It calculates all the values in the array and returns the calculated value, while array_map calculates the values under each key and returns the array
// Not too clear. check the manual for an instance.
Echo'

';
//---------------------------------------------
// Array_replace ($ array, $ parArr ,...)
// Replace the value of the same key in $ array with the value of the key in the parameter array
// If the corresponding key is not found in the parameter array behind the $ array, add it to the back of the new array.
/* $ Arr = getArr (4, 10 );
$ Arr2 = getArr (6, 15 );
Printr ($ arr );
Printr ($ arr2 );*/
$ Base = array ('citrus '=> array ("orange"), 'Berries' => array ("blackberry", "raspberry "),);
$ Replacements = array ('citrus '=> array ('pineapple'), 'Berries' => array ('Blueberry '));
Printr (array_replace ($ base, $ replacements ));
Echo'

';
//---------------------------------------------
// Array_replace_recursive () recursive replacement
// Functions are the same as array_replace. The difference is that array_replace_recursive () can operate on multi-dimensional arrays without changing the $ array structure. array_replace () will return a one-dimensional array.
$ Base = array ('citrus '=> array ("orange"), 'Berries' => array ("blackberry", "raspberry "),);
$ Replacements = array ('citrus '=> array ('pineapple'), 'Berries' => array ('Blueberry '));
Printr (array_replace_recursive ($ base, $ replacements ));
Echo'

';
//---------------------------------------------
// Array_reverse ($ arr)
// Sort the keys in the array in reverse order
Echo'

';
//---------------------------------------------
// Array_search ($ value, $ array)
// Find the key name with the value of $ value in the $ array
// If no value is found, false is returned.
// If the $ array has multiple $ values, only the first matched Key is returned.
// This function is similar to array_keys (). The difference is that: array_search () returns only one matching key name, while array_keys () returns a one-dimensional array consisting of all matching keys.
Echo'

';
//---------------------------------------------
// Array_shift ($ arr)
// Remove the first key in the current $ arr array and re-orchestrate the subsequent numeric indexes (without changing the original order). non-numeric indexes remain unchanged.
// This function is similar to array_pop (). The difference is that array_pop () is the last one, and array_shift () is the last one.
Echo'

';
//---------------------------------------------
// Array_slice ($ arr, $ offset, $ length = 0, false) array truncation
// Returns the offset starting from $ offset in the current $ arr array. a total of $ length elements/keys are returned in a new array.
// If $ offset or $ length is negative, it is offset in the opposite direction.
// It feels similar to substring () string truncation
// Directly use the instance in the php Manual
$ 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
Printr (array_slice ($ input, 2,-1 ));
Printr (array_slice ($ input, 2,-1, true ));
Echo'

';
//---------------------------------------------
// Array_spslice ($ arr, $ offset, $ length)
// Opposite to the array_slice () function, this function removes the elements between $ offset and $ length.
Unset ($ arr );
Echo'

';
//---------------------------------------------
// Array_sum ($ arr)
// Sum and accumulate all values in the $ arr array. if it is not of the numerical type, the conversion is attempted, but most of the values are 0.
// This function only affects an array, which is similar to array_product ().
$ Arr = array (
45, 56, 'A', 'B' => getArr (1, 2 ),
);
Printr ($ arr );
Echo 'Array _ sum ($ arr) ', array_sum ($ arr );
Echo'

';
//---------------------------------------------
// Array_values ($ arr)
// Extract the value from the $ arr array to form a new array
$ Arr = array (
'K1 '=> 45, 'K2' => 56, 'k3' => 'A', 'B' => getArr (1, 2 ),
);
Printr (array_values ($ arr ));
Echo'

';
//---------------------------------------------
// Array_unique ($ arr) duplicates the array
// Sort the values of the $ arr array to filter repeated values. Only the first value is retained for multiple identical values.
Echo'

';
//---------------------------------------------
// Array_walk ($ arr, callback [callback function], $ sel_perfix = '')
// Send each key in the current array to the callback function for processing.
// If the $ sel_perfix parameter is added, the callback function must receive three parameters. Otherwise, an error is returned.
// This function only affects one layer
$ Fruits = array ("d" => "lemon", "a" => "orange", "B" => "banana ", "c" => "apple ");
Function test_alter (& $ item1, $ key, $ prefix)
{
$ Item1 = "$ prefix: $ item1 ";
}
Printr (array_walk ($ fruits, 'Test _ print '));
Array_walk ($ fruits, 'Test _ alter ', 'fruit ');
Echo'

';
//---------------------------------------------
// Array_pai_recursive ()
// The function is similar to array_alk (). However, it recursion $ arr's array layer, and the returned array does not change the structure of the original array.
Echo'

';
//---------------------------------------------
// Arsort ($ arr)
// Sort the array by the array key name to sort the letters. If the sorting fails, null is returned.
Echo'

';
//---------------------------------------------
// Asort ()
// The function is similar to arsort (). The difference is that asort () sorts values.

Array loop

The code is as follows:
Foreach ($ array as $ value ){
Echo $ value;
}
While (list ($ key) = each ($ array )){
Echo $ array [$ key];
}
Foreach ($ array as $ value ){
Echo $ value;
}
While (list ($ key) = each ($ array )){
Echo $ array [$ key];
}

When the array "write" operation is performed in a loop, while is faster than foreach:

The code is as follows:

Foreach ($ array as $ key => $ value ){
Echo $ array [$ key] = $ value .'...';
}
While (list ($ key) = each ($ array )){
$ Array [$ key] = $ array [$ key]. '...';
}
Foreach ($ array as $ key => $ value ){
Echo $ array [$ key] = $ value .'...';
}
While (list ($ key) = each ($ array )){
$ Array [$ key] = $ array [$ key]. '...';
}

Conclusion: foreach is usually considered to be slower than while when it involves value replication, but in fact, if it is just a read operation on the array in a loop, foreach is very fast, this is because the replication mechanism adopted by PHP is "reference replication, write copy". In this way, it is not difficult to understand the efficient read operations of foreach.

In addition, since foreach is not suitable for array write operations, we can draw a conclusion that, in most cases, it is similar to foreach ($ array as $ key => $ value) all code in the form should be replaced with while (list ($ key) = each ($ array )).

Every ID key in the array associated with an array with the numeric ID key is associated with an array of values multi-dimensional arrays containing one or more arrays. All right...

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.