Arrays and data structures for PHP

Source: Internet
Author: User
Tags http cookie http file upload http post

Arrays in PHP
Array Overview---PHP is a weakly typed language, so the array can hold any number, any type of data, and can implement the functions of heap, stack, queue and other data structures. The array capacity can be adjusted automatically based on the number of elements.

Classification
An indexed array---subscript is an integer, similar to an array in most languages.
Associative array---Subscript is an unordered, non-repeating key that maps to the corresponding value.

(i) Definition of an array
1, the direct assignment of the way to declare an array
Use a string to declare an associative array by using a number in the square brackets "[]" after the variable name to declare an indexed array.
$ array variable name [index value]= data content//Where index value (subscript) can be a string or an integer
When declaring an array variable, you can also use the number and string blending methods in the subscript. But this approach is rarely used for one-dimensional arrays
$contact [0]=1
$contact ["id"]=1
$contact [1]= "a Company"
$contact ["Company"]= "a Company"
An array $contact is declared in the previous code, where a combination of numbers and strings is used in the subscript. This can be accessed either by indexing or by using an associated method.
When declaring an indexed array, if the index value is incremented, you can specify an index value within the square brackets, which increments by default starting at 0. The subscript value of an indexed array in PHP can be non-contiguous, as long as the non-contiguous subscript value is specified at initialization time.
$contact []=1; The default subscript is 0
$contact [14]= "Gao MoU"; Specifies a non-contiguous subscript of 14
$contact []= "a company"; Follow the highest subscript value and add 1 to the subscript 15
$contact [14]=110; The element with subscript 14 is re-assigned
$contact []= "PHP"; or follow the highest subscript value and add 1 after the subscript is 16
Print_r ($contact); Array ([0] = 1 [+] = [+] [] + a company [+] = PHP)

2. Declaring an array using the array () language structure
You can use the array () language structure to create a new array. It accepts any number of key (key) = = VALUES (value) pairs separated by commas.
$ array variable name =array (key1=>value1,key2=>value2,..., Keyn=>valuen,)//Key (key) is an integer or string value (value) that can be any type of value
If you do not use + = To specify that the subscript defaults to an indexed array, the index value is incremented by default starting with 0. If you do not want to use the default index value when declaring an array using the array () language structure, you can use the = = operator to specify non-contiguous index values. The code is as follows
$contact =array (1,14=> "Gao MoU", Company A, 14=>110,php);
Print_r ($contact); Array ([0] = 1 [+] = [+] [] + a company [+] = PHP)
Note: You should always enclose the array index with a string representation. For example, use $foo [' Bar '] instead of $foo [bar]. But this does not mean that you always enclose the key name in quotation marks. You do not need to enclose the key name as a constant or a variable, otherwise it will make PHP unable to parse it.
(ii) traversing an array
1. Iterating through an array using the For statement
Using the For statement to iterate through an array requires that the subscript of the array must be a sequential numeric index, whereas in PHP you can specify not only discontinuous numeric index values, but also associative arrays with strings as subscripts, so it is seldom used in PHP to iterate through an array with a for statement.

2. Iterating through an array using a foreach statement
The foreach syntax structure provides an easy way to iterate through an array. foreach can only be applied to arrays and objects (PHP5 supports traversing objects), and if an attempt is applied to a variable of another data type, or an uninitialized variable, it will result in an error. There are two kinds of syntax:
foreach (array_expression as $value) {
First Kind
}
foreach (array_expression as $key = = $value) {
The second Kind
}
Read more about foreach in the official PHP brochure

3. Use the list (), each () and while loop to iterate through the array
each ()--Returns the key/value pair at the current pointer position in array arrays and moves the array pointer forward. After each (), the array pointer stays in the next cell in the array, or when the end of the array is encountered, the last cell. If you want to iterate through the array again, you must use Reset ().
List ()--assigns the values in the array to some variables. Like Array (), this is not a real function, but a language structure. List () assigns a set of variables in one-step operation. List () can only be used for arrays of numeric indexes and assumes that the numeric index starts at 0.
Additional notes:
each () reads an element each time it is assembled into an array and returns false without an element. The returned array key is named 0,1,key,value, where 0 and key are equal, and 1 and value are equal.
List (), which is syntactically odd, is used only for numeric indexed arrays, and assumes that the index starts at 0. List (,, Var) =array;
while (list (key,value) = each ($array)) {}

4. Iterating through an array using the internal pointer control function of an array
For the control of array pointers, PHP provides several built-in functions:
-->current ()-Get the current pointer position content data
-->key ()-Gets the index value of the current pointer position
-->prev ()-Returns the internal pointer of the array back to a
-->next ()-Moves the inner pointer in the array forward one
-->end ()-Points the inner pointer of the array to the last cell
-->reset ()-Points the inner pointer of the array to the first cell

(c) pre-defined arrays
Starting with php4.1.0, PHP provides an additional set of predefined arrays that contain data from the Web server, client, runtime environment, and user input. They are automatically enforced at the global scope, so they are often referred to as automatic global variables or hyper-global variables. In PHP, users cannot customize hyper-global variables, so you should avoid having the same name as a predetermined global variable when customizing variables. The common global array is as follows
-$GLOBALS-referencing all the variables available in the global scope
-->$_server-Server and execution Environment information
-->$_env-Environment variables
-->$_get-http GET Variable
-->$_post-http POST variables
-->$_request-http REQUEST variable, by Get,post. The variables that the cookie submits to the script are not trustworthy
-->$_files-http File Upload variables
-->$_session-session variable
-->$_cookie-http cookies, variables submitted to the script via an HTTP COOKIE

(iv) related processing functions of arrays
1. Key value operation function of array
-->array_values (): Returns all values in the array
-->array_keys (): Returns all the key names in the array
-->in_array (): Checks if a value exists in the array, that is, searches the array for the given value. Array_search () can also be used.
-->array_key_exits (): Checks whether the given key name or index exists in the array
-->array_flip (): Swaps the keys and values in the array and returns an array after the interchange. If a value exists more than once, the most key name overrides the previous value as its value
-->array_reverse (): Flips the order of elements in the array, creates a new array, and returns. That is, the array elements are sorted in reverse order.

2, the number and uniqueness of the statistical array elements
-->count (): Counts the number of elements in an array or the number of attributes in an object
-->array_count_values (): Counts the number of occurrences of all values in the array
-->array_unique (): Removes duplicate values from the array and returns the new array

3. Functions for handling arrays using callback functions
-->array_filter (): Filters the elements in an array with a callback function, returning a new array filtered by the user-defined function
-->array_walk (): The callback function is applied to each element in the array, which returns true otherwise false
-->array_map (): Functions The callback function on the element of the given array (multiple arrays can be processed), returning the array after the user-defined function
-->array_filter (): Filters the elements in an array with a callback function, returning a new array filtered by the user-defined function
-->array_filter (): Filters the elements in an array with a callback function, returning a new array filtered by the user-defined function

4. Sorting Functions for arrays


5. Splitting, merging, decomposing, and combining arrays
-->array_slice (): Takes a value out of a condition in the array and returns
-->array_splice (): Select a value in the array to delete them or replace them with other values.
-->array_combine (): Creates an array with the value of an array as its key name, and the value of another array as its value
-->array_merge (): Merging one or more arrays
-->array_intersect (): Computes the intersection of an array
-->array_diff (): Computes the difference set of an array
-->array_slice (): Takes a value out of a condition in the array and returns

6. Other common functions
-->array_rand (): Randomly fetching one or more elements from an array
-->shuffle (): Disrupts the order of elements in the array
-->array_sum (): Computes the and of all values in the array
-->range (): Create an array containing the specified range of cells

(v) Arrays and data Structures
In a strongly typed programming language, there is a dedicated data structure solution. Typically, you create a container in which you can store any type of data, and you can determine the container's capacity based on the data stored in the container, hitting a container structure that can be long, such as linked lists, stacks, and queues, which are commonly used in data structures. In PHP, it is common to use arrays to accomplish the work of other languages using data structures. It is a type of language, in the same array can be stored in many types of data, and PHP arrays do not have a length limit, the capacity of the array storage data can also be adjusted according to the number of elements inside and out automatically.
1. Using arrays to implement stacks
The stack is a kind of realization form of data structure, which uses the data structure of "advanced after-out" when it is stored. In PHP, the array is used as a stack using Array_push () and Array_pop () two functions to complete the stack and stack operation of the data.
-->array_push (): Presses one or more cells into the end of the array (into the stack) and returns the length of the new group.
-->array_pop (): Set the array with the most one cell pop-up array (out of the stack)
2. Using arrays to implement queues
The queue is an implementation form of data structure, which uses the "FIFO" data structures when it is stored. In PHP, the array is used as a stack using Array_push () and Array_shift () two functions to complete the queue operation of the data.
-->array_shift (): Moves the cell at the beginning of the array to a group, and then returns the value of the deleted element.
-->array_shift (): Inserts one or more cells at the beginning of the array

Arrays and data structures for PHP

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.