Home > Backend Development > PHP Tutorial > PHP arrays and data structures

PHP arrays and data structures

不言
Release: 2023-04-02 16:06:02
Original
1762 people have browsed it

This article mainly introduces the arrays and data structures of php, which has certain reference value. Now I share it with you. Friends in need can refer to

Arrays in php
Array overview --- PHP is a weakly typed language, so arrays can store any number of data of any type, and can realize the functions of data structures such as heaps, stacks, and queues. The array capacity can be automatically adjusted according to the number of elements.

Classification
Index array---the subscript is an integer, similar to arrays in most languages.
Associative array---The subscript is an unordered and non-repeating key, which is mapped to the corresponding value.

(1) Definition of array
1. Declare the array by direct assignment
Use numbers in square brackets "[]" after the variable name to declare the index array and use strings Declare an associative array.
$Array variable name [index value] = data content //The index value (subscript) can be a string or an integer
When declaring an array variable, you can also use a mixture of numbers and strings in the subscript The way. But this method is rarely used for one-dimensional arrays
$contact[0]=1
$contact["id"]=1
$contact[1]="Company A"
$contact["Company"]="Company A"
In the above code, an array $contact is declared, in which a mixture of numbers and strings is used in the subscript. This can be accessed using index or relational methods.
When declaring an index array, if the index value is increasing, you do not need to specify the index value in square brackets. By default, it starts from 0 and increases in sequence. In PHP, the subscript values ​​of the index array can be non-consecutive, as long as the non-consecutive subscript values ​​are specified during initialization.
$contact[]=1; //The default subscript is 0
$contact[14]="Gao"; "Company A"; //Follow the highest subscript value and add 1, the subscript is 15
$contact[14]=110; //The element with the subscript 14 is reassigned
$contact[ ]="php";                                                                                           use   using using using                   ‐ ‐             off out          out out of ‐ out out off ‐ ‐ ‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ; 110 [15] => Company A [16] => php )

2. Use the array() language structure to declare an array
You can use the array() language structure to create a new array. It accepts any number of comma-separated key => value pairs.
$Array variable name=array(key1=>value1,key2=>value2,...,keyN=>valueN,) // Key (key) can be an integer or string value (value) It can be any type of value
If you do not use => to specify the subscript, it will default to an index array, and the index value will increase sequentially starting from 0 by default. If you do not want to use the default index value when declaring an array using the array() language construct, you can use the => operator to specify non-consecutive index values. The code is as follows
$contact=array(1,14=>"Gao", Company A,14=>110,php);
print_r($contact); > 1 [14] => 110 [15] => Company A [16] => php )
Note: Array indexes expressed as strings should always be enclosed in quotes. For example, use $foo['bar'] instead of $foo[bar]. But that doesn't mean you always put quotes around key names. There is no need to quote the key names of constants or variables, otherwise PHP will not be able to parse them.

(2) Traverse the array
1. Use the for statement to loop through the array Using the for statement to traverse the array requires that the subscript of the array must be a continuous numeric index, and in PHP Not only can you specify non-consecutive numeric index values, but there are also associative arrays with strings as subscripts, so the for statement is rarely used in PHP to loop through arrays.

2. Use the foreach statement to loop through the array
The foreach syntax structure provides a simple way to traverse the array. foreach can only be applied to arrays and objects (it supports traversing objects since PHP5). If you try to apply it to variables of other data types, or uninitialized variables, it will cause an error. There are two syntaxes:

 foreach (array_expression as $value){
        第一种
    }
Copy after login
 foreach (array_expression as $key => $value){
        第二种
    }
Copy after login

For more information about foreach, please refer to the PHP official manual

3. Combined use of list(), each() and while loop to traverse the array
each()--returns the key/value pair of the current pointer position in the array array and moves the array pointer forward. After each() is executed, the array pointer will stay at the next element in the array or at the last element when the end of the array is reached. If you want to use each to iterate through the array again, you must use reset().
list()--Assign the values ​​in the array to some variables. Like array(), this is not a real function, but a language construct. list() assigns values ​​to a set of variables in one step. list() can only be used with numerically indexed arrays and assumes that numerical indexing starts at 0.
Supplementary instructions:
Each() reads an element each time and assembles it into an array and returns it. If there are no elements, it returns false. The returned array key names are 0,1,key,value, where 0 is equal to key and 1 is equal to value.
list(), with weird syntax, is only used to numerically index arrays, and assumes that the index starts from 0. list(,,var)=array;
while(list(key,value) = each($array)){}

4. Use the internal pointer control function of the array to traverse the array
For the control of the array pointer, PHP provides several built-in functions:
-->current() - Get the content data of the current pointer position
-->key() - Get the index value of the current pointer position
-->prev() - Rewind the internal pointer of the array one digit
-->next() - Return Move the internal pointer in the array forward one bit
-->end() - Point the internal pointer of the array to the last element
-->reset() - Point the internal pointer of the array to the first Unit

(3) Predefined arrays
Starting from php4.1.0, PHP provides a set of additional predefined arrays. These array variables include variables from the web server and client. , operating environment and user input data. They automatically take effect in the global scope, so they are often called automatic global variables or superglobal variables. In PHP, users cannot customize super global variables, so when customizing variables, you should avoid having the same name as a predetermined global variable. Commonly used global arrays are as follows
-->$GLOBALS — References all variables available in the global scope
-->$_SERVER — Server and execution environment information
-->$_ENV — Environment Variable
-->$_GET — HTTP GET Variable
-->$_POST — HTTP POST Variable
-->$_REQUEST — HTTP Request variable, consisting of GET, POST. COOKEEVariables submitted to the script are not worthy of trust
-->$_FILES — HTTP file upload variables
-->$_SESSION — Session variables
-->$_COOKIE — HTTP Cookies, via Variables submitted by http cookie to the script

(4) Array-related processing functions
1. Array key-value operation functions
-->array_values(): Return All values ​​in the array
-->array_keys(): Returns all key names in the array
-->in_array(): Checks whether a certain value exists in the array, that is, searches for a given value in the array value. Array_search() can also be used.
-->array_key_exits(): Check whether the given key name or index exists in the array
-->array_flip(): Exchange the keys and values ​​in the array and return the exchanged array. If a value exists multiple times, the last key name will be used as its value to overwrite the previous value
-->array_reverse(): Reverse the order of the elements in the array, create a new array and return it. That is, arrange the array elements in reverse order.

2. Count the number and uniqueness of array elements
-->count(): Calculate the number of elements in the array or the number of attributes in the object
-->array_count_values( ): Count the number of occurrences of all values ​​in the array
-->array_unique(): Delete duplicate values ​​in the array and return a new array

3. Functions that use callback functions to process arrays
-->array_filter(): Use the callback function to filter the elements in the array and return a new array filtered by the user-defined function
-->array_walk(): Apply the callback function to each element in the array , returns TRUE if successful, otherwise returns FALSE
-->array_map(): Apply the callback function to the elements of the given array (can handle multiple arrays), and return the array after the user-defined function is applied
- ->array_filter(): Use the callback function to filter the elements in the array, and return the new array filtered by the user-defined function
-->array_filter(): Use the callback function to filter the elements in the array, and return the new array filtered by the user-defined function New array filtered by custom function

4, Array sorting function


5, Split, merge, decompose and combine arrays
-->array_slice() : Take out a value in the array based on conditions and return
-->array_splice(): Select a value in the array based on conditions, delete them or replace them with other values
-->array_combine(): Create a Array, using the value of one array as its key name and the value of another array as its value
-->array_merge(): Merge one or more arrays
-->array_intersect(): Calculate the array Intersection
-->array_diff(): Calculate the difference set of arrays
-->array_slice(): Take out a value in the array based on conditions and return it

6. Other commonly used functions
-->array_rand(): Randomly remove one or more elements from the array
-->shuffle(): Shuffle the order of elements in the array
-->array_sum(): Calculate the sum of all values ​​in an array
-->range(): Create an array containing units in the specified range

(5) Arrays and data structures
In strongly typed programming languages, there are dedicated data structures solution. Usually, a container is created, in which any type of data can be stored. The capacity of the container can be determined based on the data stored in the container, and the container structure can be variable in length, such as linked lists, stacks, queues, etc., which are all data structures. commonly used forms. In PHP, arrays are usually used to complete work that can be done using data structures in other languages. It is a type language that can store multiple types of data in the same array, and there is no length limit for arrays in PHP. The capacity of the array to store data can also be automatically adjusted according to the increase or decrease in the number of elements inside.
1. Use arrays to implement stacks
The stack is a form of implementation of a data structure. The "first in, last out" data structure is used for data storage. In php, treat the array as a stack and use the two functions array_push() and array_pop() to complete the push and pop operations of data.
-->array_push(): Push one or more units to the end of the array (push onto the stack), and then return the length of the new group.
-->array_pop(): Pop the last unit of the array into the array (pop off the stack)
2. Use array to implement queue
Queue is an implementation form of data structure, and " "First in, first out" data structure. In PHP, you can use the array_push() and array_shift() functions to complete the data queue operation by treating the array as a stack.
             -->array_shift(): Move the unit at the beginning of the array out of the array, and then return the value of the deleted element.
         -->array_shift(): Insert one or more units at the beginning of the array

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please Follow PHP Chinese website!

Related recommendations:

How to assign values ​​in an array to a set of variables in PHP

PHP background comments Implementation

The above is the detailed content of PHP arrays and data structures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template