Summary of how PHP arrays are used

Source: Internet
Author: User
Tags explode scalar shuffle sorts
Working with arrays
An array is a variable that can store a set or series of values. An array can have a number of elements. Each element has a value, such as text, a number, or another array. An array containing other arrays is called a multidimensional array.

What is an array
A scalar variable is a named range that is used to store numeric values. Similarly, an array is a named range used to store a series of variable values, so you can use arrays to organize scalar variables.
The values stored in the array are called array elements. Each array element has an associated index (also called a keyword) that can be used to access the element. In most programming languages, arrays have numeric indexes, and these are usually started from 0 or 1.

Numeric index Array
In PHP, the default value for a numeric index starts at 0, and of course it can be changed.
1. Initialization of numeric indexed arrays
$porducts = Array (' Tires ', ' oil ', ' Spark plugs ');
Just like the Echo statement, array () is actually a language structure, not a function.
Depending on the requirements of the array contents, it may not be necessary to manually initialize them as in the example above. If the desired data is stored in another array, you can simply copy the array to another array using the operator "=".
If you need to keep the numbers in ascending order in an array, you can use the range () function to create the array automatically. The following line of code will create an array of numbers from 1 to 10: $numbers = range (1,10);
The range () function has an optional third parameter, which allows you to set the steps between values. For example, if you want to create an odd array between 1 and 10, you can use the following code: $ODDS = Range (1,10,2);
The range () function can also manipulate characters, such as: $letters = Range (' A ', ' Z ');
2. Accessing the contents of an array
To access the contents of a variable, you can use its name directly. If the variable is an array, you can use a combination of the variable name and keyword or index to access its contents. The keyword or index specifies the variable that we want to access. The index is enclosed in square brackets after the variable name.
In the default case, the 0 element is the first element of the array.
Note that although the string parsing feature of PHP is very powerful and intelligent, it can cause confusion. When you embed arrays or other variables in double-quoted strings, you can place them outside the double quotation marks if they are not interpreted correctly, or find a more complex syntax for "string manipulation and regular expressions" in the 4th chapter.
Just like other variables in PHP, arrays do not need to be pre-initialized or created. They are created automatically the first time they are used.
3. Using a loop to access an array
Because the array uses an ordered number as the index, it is easy to display the contents of the array using a for loop.
for ($i =0; $i <3; $i + +)
echo "$products [$i]";
Using a simple loop, you can access each element as a very good feature of a numeric index array. You can also use a Foreach loop, which is specifically designed for arrays. Such as:
foreach ($products as $current)
Echo $current. ' ';

Using arrays of different indexes
PHP also supports related arrays. In the related array, you can associate each variable value with any keyword or index.
1 Initializing related arrays
The code shown below can create a related array with the product name as the keyword and the price as the value:
$prices = Array (' Tires ' =>100, ' oil ' =>10, ' Spark plugs ' =>4);
The symbol between the keyword and the value is just a greater than sign with the equals sign.
2 Accessing array elements
Similarly, you can use variable names and keywords to access the contents of an array. For example $prices[' Tires ').
3 Using Loop statements
Because the index of the associated array is not a number, it is not possible to use a simple counter in the FOR Loop statement to operate on the array. However, you can use the Foreach Loop or the list () and each () structure.
The foreach () loop has a different structure when working with a related array using the Foreach Loop statement. You can use keywords as follows:

foreach ($prices as $key + $value) echo $key. ' = '. $value. ' <br/> '; The code shown below will print the contents of the $prices array using the each () structure: while ($element = each ($prices)) {echo $element [' key '];echo '-'; echo $ element[' value '];echo ' <br/> ';}

The each () function returns the current element of the array and the next element as the current element. Because the each () function is called in the while loop, it returns each element in the array sequentially, and when it reaches the end of the array, the loop operation terminates.
In this code, the variable $element is an array. When each () is called, it returns an array with 4 numeric values and 4 indexes that point to the array position. The position key and 0 contain the keywords for the current element, while the position value and 1 contain the values of the current element. Although this is not the same as choosing which method, we have chosen to use a named location instead of a numeric index location.
In addition, there is a more advanced and common way to accomplish the same operation. The function list () can be used to decompose an array into a series of values. The two values returned by the function each () can be separated by the following method: List ($product, $price) = each ($price);
The code above uses each () to remove the current element from the $prices array and return it as an array, and then point to the next element. It also uses the list () to change the array returned from each () to 0, 12 elements to two new amounts named $product and $price.
We can iterate through the entire $prices array and display its contents using a short script such as the following:

while (list ($PRODCT, $pirce) = each ($prices)) echo "$product-$price <br/>";

The output of this code is the same as the output from the previous script, but it is easier to read because list () allows naming the new variable.
One thing to note is that when you use the each () function, the array records the current element. If you want to use the array two times in the same script, you must reset the current element to the beginning of the array using the function reset (). To traverse the prices array again, you can use the following code:
Reset ($prices);
while (list ($product, $price) = each ($prices))
echo "$product-$price <br/>";

Array operators
+ union, = = equivalence, = = = identical,! = Not equivalent,<> not equivalent,!== not identical.
The Union operator attempts to add an element from $b to the end of $ A. If the element in $b has the same index as some elements in $ A, they will not be added. That is, the element in $ A will not be overwritten.

Multidimensional arrays
An array is not necessarily a simple list of keywords and values--each location in the array can also hold another array. Using this method, you can create a two-dimensional array. You can think of a two-dimensional array as a matrix, or a network with width and height, or rows and columns.

Array sorting
1 using the sort () function
The sort () function is letter-case-sensitive. All the letters are in front of the lowercase letters. So ' a ' is less than ' Z ', and ' Z ' is less than ' a '.
The second parameter of the function is optional. This optional parameter can be passed Sort_regular (default), Sort_numeric, or sort_string. The ability to specify sort types is useful, for example, when you want to compare strings that may contain numbers 2 and 12. From a mathematical point of view, 2 is less than 12, but as a string, ' 12 ' is less than ' 2 '.
2 Sorting related arrays using the Asort () function and the Ksort () function
The function Asort () is sorted according to the value of each element of the array. The Ksort () function is sorted by keyword rather than by value.
3 Reverse Sort
The function rsort () sorts a one-dimensional numeric index array in descending order. The function arsort () sorts a one-dimensional correlation array in descending order of the value of each element. The function krsort () pin sorts a one-dimensional array in descending order based on the keyword of the array element.
To access data in a one-dimensional array, you need to use the name of the array and the index of the element, except that an element has two indexes--the two-dimensional array and the one-dimensional array are similar, in addition to the rows and columns.
You can use the dual for loop to achieve the same effect:

for ($row =0; $row <3; $row + +) {for ($column =0; $column <3; $column + +) {echo ' | '. $products [$row] [$column];|echo ' |<br/> ';}

If you use this code for a large array, it will be much simpler.
You might prefer to create a column name instead of a number. You can use the following code:

$products = Array (' Code ' = ' TIR ', ' descrīption ' = ' Tires ', ' Price ' =>100), Array (' code ' "= ' oil ', ' Des Crīption ' = ' oil ', ' price ' =>10), array (' Code ' = ' SPK ', ' descrīption ' = ' Spark plugs ', ' Price ' =>4)};

It is much easier to use this array if you want to retrieve a single value. Keep in mind that storing the described content in a column named after its name is easier to remember than saving it in the so-called first column. With descriptive indexes, it is not necessary to remember that an element is stored in the [x][y] position. Using the name of a pair of meaningful rows and columns as an index makes it easy to find the data you need.
Then we can't use a simple for loop to iterate through each column sequentially. You can use the For loop to iterate through an external numeric index array, $products. Each row of the $products array is an array with a descriptive index. Use the each () and list () functions in the while loop to traverse the entire internal array. Therefore, you need a for loop with a while loop embedded in it.

for ($row = 0; $row < 3; $row + +}{while (list ($key, $value) = each ($products [$row]) {echo "| $value";} echo ' |<br/> ';}

Three-dimensional arrays have high, wide, and deep concepts. If you can easily imagine a two-dimensional array as a table with rows and columns, you can think of a three-dimensional array as a bunch of tables like this. Each element can be referenced by layers, rows, and columns.
Depending on how you create a multidimensional array, you can create four-dimensional, five-, or six-dimensional arrays. In PHP, there is no limit to the number of array dimensions, but it is difficult to imagine an array that is more than three-dimensional. Most of the practical problems logically require only three-dimensional or less-dimensional array structures to be used.

Ordering of multidimensional arrays
It is much more complex to sort an array of more than one dimension, or not to row in alphabetical and numeric order. PHP knows how to compare two numbers or strings, but in a multidimensional array, each element is an array. PHP does not know how to compare two arrays, so you need to create a way to compare them. In most cases, the order of words and numbers is obvious-but for complex objects, there are more problems.
1 user-defined sorting
The "U" in Usort () stands for "user", because this function requires the passing of a custom-defined comparison function. The versions Uasort () and Uksort () corresponding to Asort and Ksort also require incoming user-defined comparison functions.
Similar to Asort (), Uasort () is used when sorting the values of non-numeric indexed arrays. If the value is a simple number or text, you can use Asort. If the value you want to compare is as complex as an array, you can define a comparison function and then use Uasort ().
Similar to Ksort (), use Uksort () when sorting keywords for non-numeric indexed arrays. If the value is a simple number or text, use Ksort. If the object you want to compare is as complex as an array, you can define a comparison function and then use Uksort ().
2 Reverse User sequencing
The function sort (), Asort (), and Ksort () each correspond to a reverse sort function with the letter "R". User-defined sorting does not have a reverse variant, but you can reverse-sort a multidimensional array.

Reordering an array
1 using the Shuffle () function
In earlier versions of PHP, shuffle () required that a random number generator be provided first when calling the Srand () function. Now, this step is no longer needed.
If this function is important to you, you can test it on the server before applying the function in the program.
Since it is not necessary to really reorder the entire array, the same functionality can be achieved using the Array_rand () function.
2 using the Array_reverse () function
The Array_reverse () function uses an array as a parameter to return an array with the same contents as the parameter array but in reverse order.
Because using the range () function alone creates an ascending sequence, you must use the sort () function or the Array_reverse () function to change the number in the array to descending order. Alternatively, you can use the For loop to create this array in one element at a time. Such as:

$numbers = Array (); for ($i =10; $i >0; $i-) Array_push ($numbers, $i);

A For loop can be run in descending order like this. You can set the counter
A For loop can be run in descending order like this. You can set the counter's initial value to a large number, and use the operator "--" at the end of each loop to reduce the counter by 1.
Here we create an empty array, and then use the Array_push () function to add each new element to the end of the array. Note that the function opposite Array_push () is Array_pop (), which is used to delete and return an element at the end of the array.
Alternatively, you can use the Array_reverse () function to reverse-order the array created by the range () function.
Note that the Array_reverse () function returns a modified copy of the original array. If you no longer need the original array, as in this example, you can overwrite the original version with the new copy.
If the data is just a series of integers, you can create the array in reverse order by using 1 as the third optional parameter of the range () function.

Loading an array from a file
Uses the file () function to load an entire file into an array. Each line in the file becomes an element in the array. The count () function is used to count the number of elements in the array.
Explode ("\ t", $orders [$i])
The explode () function splits the incoming string into small chunks. Each tab becomes a breakpoint between two elements. The optional parameter limit for this function can be used to limit the maximum number of blocks that are returned.
You can use many methods to extract numbers from a string. Here, we use the Intval () function. It can convert a string into an integer. This conversion is quite intelligent, it can ignore some parts, such as the label cannot be converted to a number.

Perform other array operations
1 browsing in the array: each (), current (), reset (), end (), Next (), POS (), and Prev ()
As mentioned earlier, each array has an internal pointer to the current element in the array. This pointer is used indirectly when the function each () is used, but it can also be used and manipulated directly.
If a new array is created, the current pointer is initialized and points to the first element of the array.
Calling next () or each () causes the pointer to move forward one element. Calling each ($array _name) returns the current element before the pointer moves forward one position. The next () function is somewhat different--calling next ($array _name) moves the pointer forward and then returns the new current element.
Call End ($array _name) to move the pointer to the end of the array.
To traverse an array backwards, you can use the end () and Prev () functions. The Prev () function is the opposite of the next () function. It is to move the current pointer back one position and then return the new current element.
2 Apply any function to every element of an array: Array_walk ()
The Array_walk () function requires three parameters. The first is arr, which is the array that needs to be processed. The second is the Func, which is the function that the user customizes and will act on each element in the array. The third parameter, UserData, is optional, and if it is used, it can be passed as a parameter to our own function.
See an example of a pin slightly complex point:

Function my_multiply (& $value, $key, $factor) {$value *= $factor;} Array_walk (& $array, ' my_multiply ', 3);

Here, we define a function called my_multiply () that can be multiplied by the provided multiplication factor to multiply each element in the array.
In addition, there is a need to pay attention to the problem is the way to pass 毵 number $value. In the function definition of my_multiply (), the address character (&) preceding the variable means that $value is passed by reference. Passing by reference allows the function to modify the contents of an array.
3 counts the number of array elements: count (), sizeof (), and Array_count_values ()
The Count () function and the sizeof () function have the same purpose and can return the number of array elements. You can get the number of elements in a regular scalar variable, if the array passed to the function is an empty array, or is an array of variables that are not set, the number of returned arrays is 0.
If you call Array_count_values ($array), this function will count the number of times each particular value has occurred in the array $array (this is the set of base numbers for the array). This function will return a related array containing the frequency table. This array contains all the values in the array $array and takes these values as keywords for the related array. The value for each keyword is the number of occurrences of the keyword in the array $array.
4 converts an array into a scalar variable: extract ()
for a non-numeric indexed array with many keyword-value pairs, you can use the function extract () to convert them to a series of scalars. The purpose of the
function extract () is to create a series of scalar variables through an array whose names must be the names of the keywords in the array, while the values of the variables are the values in the array. The
Extract () function has two optional parameters: Extract_type and prefix. The variable extract_type will tell the extract () function How to handle the conflict. Sometimes a variable with the same name as the array keyword may already exist, and the default action of the function is to overwrite the existing variable. The
Two most common options are extr_overwrite (default) and Extr_prefix_all. Other options may be used when you know that a particular conflict occurs and you want to skip the keyword or prefix it.
Extract () can extract an element that has a keyword that is a valid variable name, which means that keywords that start with a number or that contain spaces are skipped.

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.