How to use PHP arrays

Source: Internet
Author: User
Tags compact
This article mainly introduces the use of PHP arrays, has a certain reference value, now share to everyone, the need for friends can refer to

In this tutorial I will use some practical examples and best practices to enumerate the commonly used array functions in PHP. Each PHP engineer should have a grasp of how they are used, and how to write more streamlined and readable code using a combination.

In addition, we provide a presentation of the relevant sample code that you can download from the relevant links and share it with your team to build a stronger team.

Entry

Let's start with some basic array functions that deal with array key names and key values. Array_combine () as a member of an array function, is used to create a new array by using the value of one array as its key name, and the value of another array as its value:

<?php$keys = [' sky ', ' grass ', ' orange ']; $values = [' Blue ', ' green ', ' orange ']; $array = Array_combine ($keys, $values);p Rint_r ($array);//array//(//     [Sky] = blue//     [Grass] = green//     [orange] = orange//)

You should know that the array_values () function returns the value in the array as an indexed array, Array_keys () returns the key name of the given array, and the Array_flip () function, which functions as the key and key names in the interchange array:

<?phpprint_r (Array_keys ($array));//[' sky ', ' grass ', ' Orange ']print_r (array_values ($array));//[' Blue ', ' green ', ' Orange ']print_r (Array_flip ($array));//array//(//     [Blue] = sky//     [Green] = grass//     [Orange] = > orange//)

Simplifying code

The list () function, rather than a function, is a language structure that assigns values from an array to a set of variables in a single operation. For example, here's a basic use of the list () function:

<?php//definition Array $array = [' A ', ' B ', ' C '];//do not use list () $a = $array [0]; $b = $array [1]; $c = $array [2];//using list () function list ($a, $b, $c) = $array;

This language structure combines preg_split () or explode () functions better, and if you don't need to define some of these values, you can skip the assignment of some parameters directly:

$string = ' Hello|wild|world '; list ($hello,, $world) = Explode (' | ', $string); Echo $hello, ', $world;

In addition, thelist () can also be used for foreach traversal, which gives the advantage of this language structure:

$arrays = [[1, 2], [3, 4], [5, 6]];foreach ($arrays as List ($a, $b)) {    $c = $a + $b;    Echo $c, ', ';}
Note: the list () language structure applies only to numeric indexed arrays, and the default index starts at 0 and cannot be used for associative arrays to view the document.

By using the Extract () function, you can export an associative array to a variable (symbol table). Each element in an array is created with its key name as the variable name, and the value of the variable is the value of the corresponding element:

<?php$array = [    ' clothes ' = ' T-shirt ',    ' size ' = ' Medium ',    ' color ' = ' blue ',];extract ($array Echo $clothes, ', $size, ', $color;

Note the extract () function is a safe function when processing user data, such as requested data, so it is better to use better flag types such as extr_if_exists and extr_prefix_all< /c11>.

The inverse operation of the extract () function is the compact () function, which is used to create an associative array from the variable name:

<?php$clothes = ' T-shirt '; $size = ' Medium '; $color = ' blue '; $array = compact (' clothes ', ' size ', ' color ');p Rint_r ($ array);//array//(//     [clothes] = t-shirt//     [size] = medium//     [color] = blue//)

Filter function

PHP provides an awesome function for filtering arrays, which is array_filter (). The pending array is the first parameter of the function, and the second parameter is an anonymous function. If you want the elements in the array to pass validation, return truein the anonymous function, otherwise return false:

<?php$numbers = [ -3, -99, +]; $positive = Array_filter ($numbers, function ($number) {    return $number > 0 ;}); Print_r ($positive);//[0, 2 = 4, 55]

Functions not only support filtering by value. You can also use array_filter_use_key or Array_filter_use_both as the third parameter to specify whether to set the key value of the array or the key and key names as arguments to the callback function.

You can also remove null values by not defining a callback function in the array_filter () function:

<?php$numbers = [-1, 0, 1]; $not _empty = Array_filter ($numbers);p rint_r ($not _empty);//[0 =-1, 2 = 1]

You can use the Array_unique () function to get a unique value element from an array. Note that the function retains the key name of the unique element in the original array:

<?php$array = [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 5]; $uniques = Array_unique ($array);p rint_r ($uniques);p rint_r ($array);//Ar ray//(//     [0] = 1//     [4] = 2//     [7] = 3//     [8] = = 4//     [9] = = 5//)

The Array_column () function can get the value of a specified column from a multidimensional array (multi-dimensional), such as obtaining an answer from a SQL database or importing data from a CSV file. You only need to pass in the array and specify the column name:

<?php$array = ['    id ' = = 1, ' title ' = ' Tree '],    [' id ' = + 2, ' title ' = ' Sun '],    [' id ' = 3, ' Title ' + ' Cloud ',]; $ids = Array_column ($array, ' id ');p rint_r ($ids);//[1, 2, 3]

Starting with PHP 7,Array_column is more powerful because it begins to support arrays containing objects, so it's easier to work with the array model:

<?php$cinemas = Cinema::find ()->all (), $cinema _ids = Array_column ($cinemas, ' id '); PHP7 forever!

Array traversal processing

By using Array_map (), you can execute a callback method on each element in the array. You can get a new array by passing in the function name or anonymous function based on the given array:

<?php$cities = [' Berlin ', ' KYIV ', ' Amsterdam ', ' Riga ']; $aliases = Array_map (' Strtolower ', $cities);p Rint_r ($aliases );//[' Berlin ', ' Kyiv, ' Amsterdam ', ' riga '] $numbers = [1,-2, 3, -4, 5]; $squares = Array_map (function ($number) {    Retu RN $number * * 2;}, $numbers);p Rint_r ($squares);//[1, 4, 9, 16, 25]

There is also a rumor about this function that it is not possible to pass the key name and key value of the array to the callback function at the same time, but we are going to break it now:

<?php$model = [' id ' = = 7, ' name ' = ' James ']; $res = Array_map (function ($key, $value) {    return $key. ' Is '. $value;}, Array_keys ($model), $model);p Rint_r ($res);//array//(//     [0] = ID is 7//     [1] = = james//)

But it's ugly to deal with it. It is best to use the Array_walk () function instead. This function behaves like array_map () , but works completely differently. First, the array is passed in as a reference value, so array_walk () does not create a new array, but modifies the original array directly. So as the source array, you can pass the value of the array to the callback function as a reference passing method, and the key name of the array is passed in directly:

<?php$fruits = [    ' banana ' = ' yellow ',    ' apple ' = ' green ',    ' orange ' = ' orange ',];array_walk ($ Fruits, function (& $value, $key) {    $value = $key. ' Is '. $value;}); Print_r ($fruits);

Array JOIN operation

The best way to combine arrays in PHP is to use the Array_merge () function. All array options are merged into an array, and values with the same key name are overwritten by the last value:

<?php$array1 = [' a ' = = ' A ', ' B ' = ' B ', ' c ' = ' C ']; $array 2 = [' a ' = = ' A ', ' b ', ' = ' B ', ' d ', ' = ' d ']; $merge = Array_merge ($array 1, $array 2);p Rint_r ($merge);//array//(//     [A] = a//     [b] = = b//     [c] = C     [D] = d//)
The
merge array operation also has a "+" operator, which is similar to the function of the array_merge () function to complete the combined array operation, but the result is different, you can view the PHP combined array operator + and the Array_merge function. To solve more details.

To implement removing values from the array that are not in the other array (note: Calculate the difference), use Array_diff (). The Array_intersect () function can also be used to get the values that exist for all arrays (get intersection). The following example shows how they are used:

<?php$array1 = [1, 2, 3, 4]; $array 2 = [3, 4, 5, 6]; $diff = Array_diff ($array 1, $array 2); $intersect = Array_intersect ($a Rray1, $array 2);p Rint_r ($diff); Difference Set [0 = 1, 1 = 2]print_r ($intersect); Intersection [2 = 3, 3 = 4]

Mathematical operations of arrays

Use Array_sum () to sum the array elements, array_product the array elements, or use Array_reduce () to process the custom operation rules:

<?php$numbers = [1, 2, 3, 4, 5];p Rint_r (array_sum ($numbers));//15print_r (Array_product ($numbers));//120print_r ( Array_reduce ($numbers, function ($carry, $item) {    return $ $carry? $carry/$item: 1;})); /0.0083 = 1/2/3/4/5

In order to achieve the number of occurrences of a value in a statistical array, you can use the Array_count_values () function. It returns a new array with the new array key named as the value of the array to be counted, and the value of the new array is the number of occurrences of the array value to be counted:

<?php$things = [' Apple ', ' apple ', ' banana ', ' tree ', ' tree ', ' tree ']; $values = array_count_values ($things);p Rint_r ($ values);//array//(//     [Apple] = 2//     [Banana] = 1//     [tree] = 3//)

Generating arrays

To generate a fixed-length array with a given value, you can use the Array_fill () function:

<?php$bind = Array_fill (0, 5, '? '); Print_r ($bind);

To create an array from a range, such as hours or letters, you can use the range () function:

<?php$letters = Range (' A ', ' Z ');p rint_r ($letters); [' A ', ' B ', ..., ' z '] $hours = range (0, 23°c);p Rint_r ($hours); [0, 1, 2, ..., 23]

To achieve a partial element in the array-for example, to get the first three elements-use the Array_slice () function:

<?php$numbers = Range (1, ten), $top = Array_slice ($numbers, 0, 3);p Rint_r ($top);//[1, 2, 3]

Sort arrays

The first thing to remember about the ordering function in PHP is that it is a reference value , and the sort success returns true if the sort failure returns false. The underlying function of the sort is the sort () function, which performs a sorted result without preserving the original index order. Sorting functions can be categorized into the following categories:

    • a keep the index relationship sorted

    • k Sort by key name

    • R to reverse-sort an array

    • u sort using user-defined collation

You can see these sort functions from the following table:


a k R u
A Asort
Arsort Uasort
K
Ksort Krsort
R Arsort Krsort Rsort
U Uasort

Usort

Array functions are used in combination

The art of array processing is to combine the use of these array functions. Here we can complete the null character interception and de-control processing with just one line of code via the array_filter () and array_map () functions:

<?php$values = [' say ', '  bye ', ' ', ' to ', ' spaces  ', '    ]; $words = Array_filter (' Trim ', $value s));p Rint_r ($words);//[' Say ', ' bye ', ' to ', ' spaces ']

Based on the model array creation ID and title data dictionary, we can use the array_combine () and the array_column () function together:

<?php$models = [$model, $model, $model]; $id _to_title = Array_combine (    array_column ($models, ' id '),    Array_ Column ($models, ' title ');p Rint_r ($id _to_title);
provide a version that can be run.

To achieve the most frequently occurring array elements, we can use the array_count_values (),arsort () , and array_slice () functions:

<?php$letters = [' A ', ' a ', ' a ', ' a ', ' B ', ' B ', ' C ', ' d ', ' d ', ' d ', ' d ', ' d ']; $values = Array_count_values ($letters); ARS ORT ($values); $top = Array_slice ($values, 0, 3);p Rint_r ($top);

You can also easily pass the array_sum () and array_map () functions to calculate the price of an order in just a few lines:

<?php$order = [    [' product_id ' + 1, ' price ' = +, ' count ' = + 1],    [' product_id ' + 2, ' price ' = =  , ' count ' = 2],    [' product_id ' = + 2, ' price ' = ', ' count ' = 3], '; $sum = array_sum (Array_map (function ($product _row) {    return $product _row[' price ' * $product _row[' count '];}, $order)); Print_r ($sum);//250

Summarize

As you can see, mastering the main array function may be our code that is leaner and easier to read. Of course, PHP provides a lot more array functions than listed, and also provides additional parameters and identification parameters, but I think this tutorial has covered the PHP developers should master the most basic.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.