Php learning array courseware

Source: Internet
Author: User
An array is a variable that can store a group or a series of values. * Arrays are a basic data type. Array functions can also implement data structures such as stacks and queues. Subscript: the identifier of an array, that is, the code of a string or integer in the array.

Several index values in the array are called dimension arrays.
Index value: an index is a structure that sorts the values of one or more columns in a database table.

Array classification
PHP arrays are divided into two types:
Index array: the index value of the index (indexed) is an integer. it starts with 0 and uses the index array to identify objects by position.
Join array: associative is associated with the index value of the string. The index value is the column name, and the term is used to access the data of the column.

Arrays are usually assigned values.
There are two ways to assign values to an array:
$ A [1] = "dsadsadsa ";
$ B [2] = "dsadsadsad ";
Use the array function:
$ A = array ("dsads", "dsadsa", 321312 );
One-dimensional array: an array is called a one-dimensional array when there is only one index value (subscript.
Format of direct array assignment:
$ Array variable name [index value] = data content;
Note: the index values can be strings or integers, but 1 and 1 are different. one belongs to the integer and the other belongs to the string.

Arrays with the same name without indexed values are arranged in order.
Instance:
$ A = array (1, 2, 3, 4, 5, 6 );
$ B = array ("one", "two", "three ");
$ C = array (0 => "aaa", 1 => "bbb", 2 => "ccc ");
$ D = array ("aaa", 6 => "bbb", "ccc ");
$ E = array ("name" => "zhang", "age" => 20 );
?>
Two-dimensional array
Multi-dimensional array format:
$ A [0] [] = "dsadas ";
$ A [0] [] = "dsadsa"; this group is 1 and 2 of the 0 index values under $
If the format is declared using the array function:
$ A = array ("dsadsa", "dsadas", 21, array ("dsadsa", "dsadas "));

Array traversal
Foreach loop structure:
Foreach only uses two formats: loop and array
Foreach (array_exprssion (array expression) as $ value );
Foreach (array_exprssion (array expression) as $ key => $ value );
The first format traverses the given array_exprssion array. The current value in each loop is assigned to $ calue, and the pointer inside the array moves one step forward.
In the second format, only the key values of the current unit are assigned to the variable $ key in each loop.
When foreach starts to execute, the pointer inside the array automatically points to the first unit. In addition, note that foreach operates on a copy of the specified array, rather than the array itself.
$ Arr = array (10, 20, 30, 40, 50, 60 );
Foreach ($ arr as $ k =>$ v ){
Echo "$ k => $ v
";
}

Output result: 0 => 10 1 => 20 2 => 30 3 => 40 4 => 50 5 => 60 // subscript => integer
Combined use of list (), each (), and while loops
Each ():
$ Arr = array (1, 2, 3, 4, 5 );
$ A = each ($ arr );
Print_r ($ );
Output result: Array ([1] => 1 [value] => 1 [0] => 0 [key] => 0)
Obtains the value subscript key of the first part of the array.
List ():
$ Arr3 = array ("a", "B", "c ");
List ($ key, $ value) = each ($ arr3 );

Echo $ key ."
". $ Value;
Output result: 0 a list () can be used to assign values to a group of variables in one step operation. it is assumed that the numeric index starts from 0.
While loop
$ Arr = array (1, 2, 3, 4, 5, 6, 7, 8, 9 ,);
While (list ($ key, $ value) = each ($ arr )){
$ Key ++;
Echo $ key. "=>". $ value;
Echo"
";
}
Echo"
";
Output result: 1 => 1 2 => 2 3 => 3 4 => 4 5 => 5 6 => 6 7 => 7 8 => 8 9 => 9
Reset () array pointer redirection
After executing each (), the array pointer will stay in the next unit of the array or stay in the last unit when it comes to the end of the array.
Is_array: checks whether the variable is an array. true or false is returned.
$ Arr = array (1, 2, 3, 4, 5, 6, "saas ");
While (list ($ k, $ v) = each ($ arr ))
{
If (is_array ($ arr ))
{
$ X + = $ v;
Echo $ x;
}
Else
{
$ X + = $ k;
}
}
This example does not fully reflect the functions of is_array, but can be referenced.
Array pointer
Next (): Moves the pointer backward.
Prve (): Moves the pointer forward
End (): points the pointer to the last element of the array.
Reset (): Moves the current pointer to the first index position unconditionally.
Syntax format: mixed next (array name)
$ Arr = (array (1, 2, 3, 4, 5 ));
Echo end ($ arr );
Output result: 5
Key () and current () and count ()
The key () function reads the index value of the data pointed to by the current pointer.
The current () function reads the content of the data pointed to by the current pointer.
The count () function is used to calculate the number of all elements in the array, that is, the function returns the length value of the target array.
Format: int count (array name );

Key (): get the key name from the joined array
$ Array = array ('fruit1' => 'apple', 'fruit2' => 'Orange ', 'fruit3' => 'grape ', 'fruit4' => 'apple', 'fruit5' => 'apple ');
While ($ fruit_name = current ($ array )){
If ($ fruit_name = 'apple '){
Echo key ($ array ).'
';
}
Next ($ array );
}
Output results: fruit1, fruit4, fruit5

Current (): returns the current unit in the array.
$ Transport = array ('foot', 'Bike', 'car', 'Plane ');
$ Mode = current ($ transport); // $ mode = 'foot ';
$ Mode = next ($ transport); // $ mode = 'bike ';
$ Mode = current ($ transport); // $ mode = 'bike ';
$ Mode = prev ($ transport); // $ mode = 'foot ';
$ Mode = end ($ transport); // $ mode = 'plane ';
$ Mode = current ($ transport); // $ mode = 'plane ';
Note: the current unit in the array is returned by the example.

Count (): calculates the number of units in the array.
$ Arr = array (1, 2, 3, 4, 5, 6 );
Echo count ($ arr );
Output result: 6

Array_change_key_case ()
Array_change_key_case returns an array of string keys in lowercase or uppercase.
Two [CASE_UPPER] Morphological functions are converted to uppercase, and [CAS_LOWER] to lowercase.
$ Input_array = array ("FirSt" => 1, "SecOnd" => 4 );
Print_r (array_change_key_case ($ input_array, CASE_UPPER ));
Output result: Array ([FIRST] => 1 [SECOND] => 4)

Array_chunk ()
The array_chunk () function splits the data content of the target array into several small arrays by specifying the number of indexes.
$ Arr = array (1, 2, 3, 4, 5, 6 );
$ A = array_chunk ($ arr, 3 );
Print_r ($ );
Output result: Array ([0] => Array ([0] => 1 [1] => 2 [2] => 3) [1] => Array ([0] => 4 [1] => 5 [2] => 6 ))
That is, it is equal to dividing by 3 by the sum of the number of array units.

Array_count_values
Array_count_values is used to calculate the number of occurrences of each value in the target array.
Syntax format: array_count_values (target array)
The result value returned by this function uses the content and data of the original array as an index and is represented as an array.
$ Arr = array (1, 2, 3, 2, 6 );
Print_r (array_count_values ($ arr ));
Output result: Array ([1] => 1 [2] => 2 [3] => 2 [6] => 1)

Array_fill
Array_fill allows you to customize the value to fill the specified index segment in the target array.
Syntax format: array_fill (starting index position, segment size, specified character)
The starting index position and segment size must be integer (integer) type values, and the segment size cannot be 0.
$ A = array_fill (5, 6, 'banana ');
Print_r ($ );
Output result: array ([5] => banana [6] => banana [7] => banana [8] => banana [9] => banana [10] => banana)

Array_filter
Array_filter transmits each value in the target array to the user-defined function in sequence. If the user-defined function returns TRUE (TRUE
), The current value of the input array is included in the returned result array. The key name of the array remains unchanged.
Syntax format: array_filter (target array, user-defined function)
Function odd ($ var)
{
Return ($ var % 2 = 1 );
}
$ Array1 = array ("a" => 1, "B" => 2, "c" => 3, "d" => 4, "e" => 5 );
Print_r (array_filter ($ array1, "odd "));
Output result: Odd: Array ([a] => 1 [c] => 3 [e] => 5)
$ Entry = array (0 => 'foo', 1 => false, 2 =>-1 => null, 4 => '');
Print_r (array_filter ($ entry ));
Output result Array ([0] => foo [2] =>-1)
Other callback functions: array_walk (), array_map ()

Array_flip
Array_flip performs reverse processing on the index and content value in the target array. the reverse array uses the original content value as the index and the index as the data content.
Array_flip syntax format: swap keys and values in an array
Array_flip (target array)
$ Trans = array ("a" => 1, "B" => 1, "c" => 2 );
$ Trans = array_flip ($ trans );
Print_r ($ trans );
Output Content: Array ([1] => B [2] => c)
If the same value appears multiple times, the last key name is used as its value, and all others are lost.

Array_sum
Array_sum is used to calculate the sum of all element values in the array.
Syntax format: array_sum (target array)

Array_unique
Array_unique is used to divide the repeated data in the target array and return a new value after calculation.

Array_keys and array_values
Array_keys this function will ignore the original key name, re-index the array using ordered numbers, for Associated arrays.
Array_values this function returns an array of key names that contain numbers or strings. Return all values in the input array and create a digital index for them.
$ Arr = array ("a" => 1, "B" => 2, "abc", 2 );
$ B = array_keys ($ arr );
$ C = array_values ($ arr );
Output result: $ B = Array ([0] => a [1] => B [2] => 0 [3] => 1)
$ C = Array ([0] => 1 [1] => 2 [2] => abc [3] => 2)

Array retrieval
Retrieving an array mainly refers to determining the key name or element value of an array to determine whether an array element exists.
Syntax format: bool in_array (mixed $ needle, array $ haystack [, bool $ strict]);
$ Arr3 = array (1, 2, 3, "hello", "wprld ");
$ B = in_array ("hell", $ arr3, true );
Var_dump ($ B );
$ Arr4 = array (1, 2, 3, array ("hello", "world "));
$ B = in_array (array ("hello", "world"), $ arr4 );
Var_dump ($ B );
Output result: bool (false) bool (true)

Conversion between arrays and variables
The extract () and compact () functions convert arrays and variables.
After conversion, the key name and variable name of the array element, and the element value and variable value maintain a corresponding relationship.
Extract: This function is used to import the variable from the array to the current symbol table.
$ Info = array ("user_id" => 2006001, "user_name" => "Xiangyu", "position" => "project manager ");
Extract ($ info );
Echo $ user_id;
Output result: 2006001
Compact () accepts variable parameter numbers. Each parameter can be a string containing the variable name or an array containing the variable name. The array can also contain an array with other units whose content is the variable name. compact () can be recursively processed.
$ City = "San Francisco ";
$ State = "CA ";
$ Event = "SIGGRAPH ";
$ Location_vars = array ("city", "state ");
$ Result = compact ("event", "nothing_here", $ location_vars );
Print_r ($ result );
Output result: Array ([event] => SIGGRAPH [city] => San Francisco [state] => CA)

Array and stack
The array_push () function pushes one or more elements to the end of the array stack (inbound stack) and returns the number of inbound stack elements.
The array_pop () function pops up the last element of the array stack and returns the element.
Example: array_push
$ A = array ("dsa", "dsas", "dfs", "gfd ");
Array_push ($ a, "ssss", "ddddd ");
Print_r ($ );
Output result: array ([0] => dsa [1] => dsas [2] => dfs [3] => gfd [4] => ssss [5] => ddddd)
The example array_pop pops up, returns the last unit of the array, and deletes the length of the array by one. If array is NULL (or not an array), NULL is returned.
$ A = array ("dsa", "dsas", "dfs", "gfd ");
Array_pop ($ );
Print_r ($ );
Output result: Array ([0] => dsa [1] => dsas [2] => dfs)

Arrays and columns
The queue can also appear as an array. The first element in the array is the opposite, and the last element is the end.
You can use the stack method to insert an element at the end.
You can use the array_shift function to delete the first element from the queue array. this function removes the first element from each other and returns the result. at the same time, the length of the array is reduced by 1, and the other elements move one digit forward. All numeric keys will be counted from scratch, and the text key name will not change.
Array_shift example
$ A = array ("dsa", "dsas", "dfs", "gfd ");
$ Title = array_shift ($ );
Print_r ($ );
Output result: Array ([0] => dsas [1] => dfs [2] => gfd)
You can use the array_unshift () function to insert one or more elements at the beginning of the queue array. This function returns the number of successfully inserted elements.
$ A = array ("dsa", "dsas", "dfs", "gfd ");
$ Title = array_unshift ($ a, "a", array (1, 2 ));
Print_r ($ );
Output result: Array ([0] => a [1] => Array ([0] => 1 [1] => 2) [2] => dsa [3] => dsas [4] => dfs [5] => gfd)
The result shows that an array can be inserted.

Sorting of arrays
Ignore array sorting of key names
Sort () normal
Rsort () inverted
Usort ()
$ Arr = array ("3" => "lemon", "2" => "orange", "4" => "banana ", "1" => "apple ");
Ksort ($ arr );
Foreach ($ arr as $ key => $ val ){
Echo "$ key = $ val \ n ";
}

Array calculation
It is convenient to calculate arrays. The simplest calculation is to calculate the sum of all elements in the array. You can also process arrays as a set, merge two or more arrays, and calculate the difference set or intersection between arrays.
Array merging is not
Example
$ Arr2 = array (1, 2, 3 );
$ Arr3 = array (3, 4, 5 );
$ A = array_merge ($ arr2, $ arr3 );
Print_r ($ );
Output result: array ([0] => 1 [1] => 2 [2] => 3 [3] => 3 [4] => 4 [5] => 5)
Calculate the difference set of an array
$ Array1 = array ("a" => "green", "red", "blue", "red ");
$ Array2 = array ("B" => "green", "yellow", "red ");
$ Result = array_diff ($ array1, $ array2 );
Print_r ($ result );
Output result: Array ([1] => blue) difference level is the difference value above.
Calculate the intersection of arrays
$ Array1 = array ("a" => "green", "red", "blue ");
$ Array2 = array ("B" => "green", "yellow", "red ");
$ Result = array_intersect ($ array1, $ array2 );
Print_r ($ result );
Output result: the intersection of Array ([a] => green [0] => red) is obtained from both the top and bottom sides.

Create an array of the specified range:
Range ();
Remove repeated values from the array:
Array_unique ();
Returns an array in reverse order:
Array_reverse ();

Random function of the array: random number
Srand (float) microtime () * 10000000) sets the random generator seed
Array_rand ();
Array_shuffle ();
Example
Echo date ("Ymd"). rand (000000,9999999). "jpg ";

Output result: the number of JPG files in 200805096246795jpg format.

The above is the content of php learning array courseware. For more information, see PHP Chinese network (www.php1.cn )!

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.