Home >Backend Development >PHP Tutorial >Everything you need to know about php arrays
The code shown below will use the each() structure to print the contents of the $prices array:
each() function will return the current element of the array and take the next element as the current element. Because each() function is called in a while loop, it will return each element in the array in order, and when it reaches the end of the array, the loop operation will terminate. In this code, the variable $element is an array. When each() is called, it returns an array with 4 numeric values and 4 indices pointing to the array positions. Positions key and 0 contain the key of the current element, while positions value and 1 contain the value of the current element. While it makes no difference which method you choose, we have chosen to use named locations rather than numerically indexed locations. Additionally, 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 as follows:
The above code uses each() to remove the current element from the $prices array, returns it as an array, and then points to the next element. It also uses list() to change the two elements 0 and 1 contained in the array returned by each() into two new variables named $product and $price. We can loop through the entire $prices array and display its contents using a short script like this:
The output of this code is the same as the output of the previous script, but it is easier to read because list() allows the new variable to be named. One thing to note is that when using the each() function, the array will record the current element. If you want to use the array twice in the same script, you must use the reset() function to reset the current element to the beginning of the array. To iterate over the prices array again, you can use code like this:
3.4 Array operators + Union, == equivalent, === identity, != not equivalent, not equivalent, !== not identical. The union operator attempts to add the elements in $b to the end of $a. If elements in $b have the same index as some elements in $a, they will not be added. That is, the elements in $a will not be overwritten. 3.5 Multidimensional array An array doesn't have to be a simple list of keys and values - each position in the array can also hold another array. Using this method, a two-dimensional array can be created. You can think of a two-dimensional array as a matrix, or a network with width and height or rows and columns. 3.6 Array sorting 3.6.1 Use the sort() function The sort() function is case-sensitive. All capital letters appear before lowercase letters. So 'A' is less than 'Z', and 'Z' is less than 'a'. The second parameter of this function is optional. This optional parameter can be passed SORT_REGULAR (default), SORT_NUMERIC or SORT_STRING. The ability to specify a sort type is useful, for example, when comparing strings that may contain the numbers 2 and 12. From a mathematical point of view, 2 is less than 12, but as a string, '12' is less than '2'. 3.6.2 Use asort() function and ksort() function to sort related arrays The function asort() sorts the array based on the value of each element. The ksort() function sorts by keyword rather than by value. 3.6.3 Reverse sorting The function rsort() sorts a one-dimensional numeric index array in descending order. The function arsort() sorts a one-dimensional associative array in descending order of the value of each element. The function krsort() sorts a one-dimensional array in descending order based on the keys of the array elements. To access data in a one-dimensional array, you use the name of the array and the index of the element. Two-dimensional arrays are similar to one-dimensional arrays, except that an element has two indices - row and column. The same effect can be achieved using a double for loop:
If you use this code for a large array, it will be much simpler. You may prefer to create column names instead of numbers. You can use the following code:
If you wish to retrieve a single value, it will be much easier to use this array. Remember to save the described content into a column named with its name. It's easier to remember than saving it into the so-called first column. With a descriptive index, you don't need to remember that an element is stored at [x][y] position. Use a meaningful pair of rows. And the column names can be used as indexes and you can easily find the required data. However, we cannot use a simple for loop to iterate through each column sequentially. You can use a for loop to iterate over the outer numerically indexed array $products. Each row of the $products array is an array with a descriptive index. Using each() and list() functions in a while loop, you can traverse the entire internal array. Therefore, a for loop with a while loop embedded inside is required.
Three-dimensional arrays have the concepts of height, width, and depth. If you can easily think of a two-dimensional array as a table with rows and columns, then you can think of a three-dimensional array as a bunch of tables like this. Each element can be referenced by level, row, and column. Depending on how you create a multidimensional array, you can create a four-, five-, or six-dimensional array. In PHP, there is no limit on the number of array dimensions, but it is difficult to imagine an array with more than three dimensions. Most practical problems logically only require the use of array structures of three dimensions or less. 3.7 Sorting of multidimensional arrays Sorting an array with more than one dimension, or sorting it out of alphabetical and numerical order, is much more complicated. PHP knows how to compare two numbers or strings, but in a multidimensional array, each element is an array. PHP doesn't know how to compare two arrays, so it needs to build a method to compare them. In most cases, the order of words and numbers is obvious—but with complex objects, it's a little more problematic. 3.7.1 User-defined sorting The "u" in usort() represents "user" because this function requires a user-defined comparison function to be passed in. The corresponding versions of asort and ksort, uasort() and uksort(), also require a user-defined comparison function to be passed in. Similar to asort(), uasort() is used when sorting values in non-numeric index arrays. You can use asort if the value is a simple number or text. If the values you want to compare are as complex as arrays, you can define a comparison function and then use uasort(). Similar to ksort(), use uksort() only when sorting by key of a non-numeric index array. Use ksort if the values are simple numbers or text. If the objects you want to compare are as complex as arrays, you can define a comparison function and then use uksort(). 3.7.2 Reverse user sorting The functions sort(), asort() and ksort() each correspond to a reverse sorting function with the letter "r". There is no reverse variant of user-defined sorting, but a multidimensional array can be sorted in reverse. 3.8 Reorder array 3.8.1 Use shuffle() function In earlier versions of PHP, shuffle() required that a random number generator be first provided when calling the srand() function. Today, this step is no longer necessary. If this function is important to you, you can test it on the server before applying it in your program. Since there is no need to actually reorder the entire array, the same functionality can be achieved using the array_rand() function. 3.8.2 Using array_reverse() function The array_reverse() function takes an array as a parameter and returns an array with the same content as the parameter array but in reverse order. Because using the range() function alone will create an ascending sequence, you must use the sort() function or the array_reverse() function to change the numbers in the array to descending order. Alternatively, you can use a for loop to create the array one element at a time. like:
A for loop can run in descending order like this. The counter can be A for loop can run in descending order like this. You can set the initial value of the counter to a large number and use the operator "--" to decrement the counter by 1 at the end of each loop. Here, we create an empty array and then add each new element to the end of the array using the array_push() function. Please note that the opposite function of array_push() is array_pop(), which removes and returns an element at the end of the array. Alternatively, you can use the array_reverse() function to reverse the array created by the range() function. Please note that the array_reverse() function will return a modified copy of the original array. If the original array is no longer needed, as in this example, the original version can be overwritten with a new copy. If the data is just a series of integers, you can create the array in reverse order by passing -1 as the third optional argument to the range() function. 3.9 Load array from file Use the file() function to load the 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 can split the incoming string into small pieces. Each tab becomes a breakpoint between two elements. The optional limit parameter of this function can be used to limit the maximum number of blocks returned. There are many methods you can use to extract numbers from strings. Here, we have used the intval() function. It converts a string into an integer. This conversion is quite intelligent and can ignore certain parts, for example labels cannot be converted to numbers. 3.10 Perform other array operations 3.10.1 Browsing in the array: each(), current(), reset(), end(), next(), pos() and prev() As mentioned earlier, every array has an internal pointer pointing to the current element in the array. When using the function each(), this pointer is used indirectly, but this pointer can also be used and manipulated directly. If you create a new array, the current pointer will be initialized and point to the first element of the array. Calling next() or each() will advance the pointer one element. Calling each($array_name) returns the current element before advancing the pointer one position. The next() function is a little different - calling next($array_name) advances the pointer and then returns the new current element. Calling end($array_name) moves the pointer to the end of the array. To traverse an array in reverse order, use the end() and prev() functions. The prev() function is the opposite of the next() function. It moves the current pointer back one position and then returns the new current element. 3.10.2 Apply any function to each element of the array: array_walk() The array_walk() function requires three parameters. The first one is arr, which is the array that needs to be processed. The second is func, which is a user-defined function that will act on each element in the array. The third parameter userdata is optional, if used it can be passed as a parameter to our own function. Let’s look at an example of a more complex point:
Here, we define a function called my_multiply() that multiplies each element in the array by the provided multiplication factor. In addition, another issue that needs attention is the way in which $value is passed. In the function definition of my_multiply(), the address character (&) in front of the variable means that $value is passed by reference. Passing by reference allows the function to modify the contents of the array. 3.10.3 Count the number of array elements: count(), sizeof() and array_count_values() The count() function and the sizeof() function have the same purpose and can both return the number of array elements. You can get the number of elements in a regular scalar variable. If the array passed to this function is an empty array, or a variable that has not been set, the number of arrays returned is 0. If you call array_count_values($array), this function will count the number of times each specific value appears in the array $array (this is the cardinality set of the array). This function will return an associated array containing the frequency table. This array contains all the values in the array $array, and uses these values as keys to the associated array. The value corresponding to each keyword is the number of times the keyword appears in the array $array. 3.10.4 Convert array into scalar variable: extract() For a non-numeric indexed array with many key-value pairs, you can use the function extract() to convert them into a series of scalar variables. The function extract() is to create a series of scalar variables from an array. The names of these variables must be the names of the keywords in the array, and the variable values 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 conflicts. Sometimes there may already be a variable with the same name as the array keyword, and the default operation of this function is to overwrite the existing variable. The two most commonly used options are EXTR_OVERWRITE (default) and EXTR_PREFIX_ALL. Additional options may be used when you know that a specific conflict will occur and you want to skip or prefix the keyword. extract() can extract an element whose keyword must be a valid variable name, which means that keywords starting with a number or containing spaces will be skipped. |