PHP arrays and data structures
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){ 第一种 }
foreach (array_expression as $key => $value){ 第二种 }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.
