Use of PHP array Road

Use of PHP array Road

This tutorial I will include an array of commonly used functions in PHP through some practical examples of ways and best practices. Each PHP engineer should master how to use them, and how to write more concise and readable code by combination.

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

getting Started

Let us start with some key names and values with arrays of basic array functions. array_combine ()  as an array function in a, for creating a new array by using an array of values as its key name, the value of another array as its value:

<?php
$keys = ['sky', 'grass', 'orange'];
$values = ['blue', 'green', 'orange'];

$array = array_combine($keys, $values);

print_r($array);
// Array
// (
//     [sky] => blue
//     [grass] => green
//     [orange] => orange
// )

You should know, array_values ()  function returns an array with an index value of the array, array_keys () will return the name given to the key array, and  array_flip ()  function, its function is to exchange an array of keys and key name:

<?php

print_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
// )

Simplify the code

list ()  function, it is not an exact function, but a language structure, can be assigned to a set of variable values in the array in a single operation. For example, given the following  list ()  basic function is used:

<?php
// 定义数组
$array = ['a', 'b', 'c'];

// 不使用 list()
$a = $array[0];
$b = $array[1];
$c = $array[2];

// 使用 list() 函数
list($a, $b, $c) = $array;

The language structure combined with  preg_split ()  or  explode ()  better use of this type of function results, if you do not need to define some of these values, you can skip some of the parameters of the assignment:

$string = 'hello|wild|world';

list($hello, , $world) = explode('|', $string);
echo $hello, ' ', $world;

In addition, List ()  can be used for  foreach  to traverse, this use of language to better take advantage of this structure:

$arrays = [[1, 2], [3, 4], [5, 6]];

foreach ($arrays as list($a, $b)) {
    $c = $a + $b;

    echo $c, ', ';
}

Translator's Note: list () language construct only for numerically indexed arrays, and the default index from  0 start, and can not be used for associative arrays, view the  document .

And through the use of  extract ()  function, you can export to an associative array variable (symbol table). Each element of the array will be created as a variable name with its key name, the value of the variable's value, compared with the corresponding elements:

<?php
$array = [
    'clothes' => 't-shirt',
    'size' => 'medium',
    'color' => 'blue',
];

extract($array);

echo $clothes, ' ', $size, ' ', $color;

Note that when the processing of user data (such as data requests)  Extract ()  function is a safety function, it is preferable to use at this time better  flag type  as  EXTR_IF_EXISTS  and  EXTR_PREFIX_ALL .

extract ()  reverse operation function is  compact ()  function is used to create an associative array variable names:

<?php
$clothes = 't-shirt';
$size = 'medium';
$color = 'blue';

$array = compact('clothes', 'size', 'color');
print_r($array);

// Array
// (
//     [clothes] => t-shirt
//     [size] => medium
//     [color] => blue
// )

Filter function

PHP provides a rocking function for the filter array, it is  array_filter () . Array to be treated as the first argument, the second argument is an anonymous function. If you want to elements in the array returned by verifying the anonymous function  to true , otherwise it returns  false :

<?php

$numbers = [20, -3, 50, -99, 55];

$positive = array_filter($numbers, function ($number) {
    return $number > 0;
});

print_r($positive);// [0 => 20, 2 => 50, 4 => 55]

Function not only supports filtering by value. You can also use  ARRAY_FILTER_USE_KEY  or  ARRAY_FILTER_USE_BOTH  as the third parameter specifies whether the array of key or keys and the keys at the same time as a parameter to the callback function.

You can not  array_filter ()  function is defined callback function to delete a null value:

<?php
$numbers = [-1, 0, 1];

$not_empty = array_filter($numbers);

print_r($not_empty);// [0 => -1, 2 => 1]

You can use  array_unique ()  function is used to obtain a unique value elements from an array. Note that the function keys will remain the only element in the original array:

<?php
$array = [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 5];

$uniques = array_unique($array);

print_r($uniques);
print_r($array);
// Array
// (
//     [0] => 1
//     [4] => 2
//     [7] => 3
//     [8] => 4
//     [9] => 5
// )

array_column ()  function to obtain the value from the column specified multi-dimensional array (multi-dimensional), the answer as acquired from the SQL database or CSV file to import data. And only need to pass an array of column names specified:

<?php
$array = [
    ['id' => 1, 'title' => 'tree'],
    ['id' => 2, 'title' => 'sun'],
    ['id' => 3, 'title' => 'cloud'],
];

$ids = array_column($array, 'id');

print_r($ids);// [1, 2, 3]

From the beginning of PHP 7, array_column  more powerful, because it began to support the  array contains objects , it becomes much easier when dealing with an array of model:

<?php
$cinemas = Cinema::find()->all();
$cinema_ids = array_column($cinemas, 'id'); // php7 forever!

Array traversal processing

By using  array_map () , you can perform the callback method for each element in the array. You can get a new array based on a given array passed to the function name or anonymous function:

<?php
$cities = ['Berlin', 'KYIV', 'Amsterdam', 'Riga'];
$aliases = array_map('strtolower', $cities);

print_r($aliases);// ['berlin', 'kyiv, 'amsterdam', 'riga']

$numbers = [1, -2, 3, -4, 5];
$squares = array_map(function ($number) {
    return $number ** 2;
}, $numbers);

print_r($squares);// [1, 4, 9, 16, 25]

For this function there is a rumor, not while the key names and values ​​of the array passed to the callback function, but we now need to break it:

<?php
$model = ['id' => 7, 'name' => 'James'];
$res = array_map(function ($key, $value) {
    return $key . ' is ' . $value;
}, array_keys($model), $model);

print_r($res);
// Array
// (
//     [0] => id is 7
//     [1] => name is James
// )

But this process it is really ugly. Preferably used  array_walk ()  function instead. This function and performance  array_map ()  is similar, but works completely different. First, the array is passed by value reference, so  array_walk ()  does not create a new array, but directly modifying the original array. So as the source array, an array of values you can pass a reference to a method passed callback function keys directly into the array like:

<?php
$fruits = [
    'banana' => 'yellow',
    'apple' => 'green',
    'orange' => 'orange',
];

array_walk($fruits, function (&$value, $key) {
    $value = $key . ' is ' . $value;
});

print_r($fruits);

Array connection operation

In the best way is to use PHP array merge  array_merge ()  function. All of the options will be merged into one array array with the same key value name will be overwritten with the last value:

<?php
$array1 = ['a' => 'a', 'b' => 'b', 'c' => 'c'];
$array2 = ['a' => 'A', 'b' => 'B', 'D' => 'D'];

$merge = array_merge($array1, $array2);
print_r($merge);
// Array
// (
//     [a] => A
//     [b] => B
//     [c] => c
//     [D] => D
// )

Annotation: merger array operations and a "+" sign of the operator, and it  array_merge ()  function is similar to function merge array operations can be done, but the results are different, you can view the  PHP array merge with array_merge function operator +  Learn more details.

To achieve the value is not deleted (Annotation: calculating a difference) another array from the array, using  array_diff () . Can also  () array_intersect  function gets the value (: Get the intersection Annotation) all arrays are present. The following example shows how to use them:

<?php
$array1 = [1, 2, 3, 4];
$array2 = [3, 4, 5, 6];

$diff = array_diff($array1, $array2);
$intersect = array_intersect($array1, $array2);

print_r($diff); // 差集 [0 => 1, 1 => 2]
print_r($intersect); //交集 [2 => 3, 3 => 4]

Math array

Use  array_sum ()  array elements summation, array_product  performs a product operation on an array element, or using  array_reduce ()  handle custom calculation rules:

<?php

$numbers = [1, 2, 3, 4, 5];

print_r(array_sum($numbers));// 15

print_r(array_product($numbers));// 120

print_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 in the value of the statistical list, you can use  array_count_values ()  function. It returns a new array of values, the new array of new key named array to be an array of statistics is the number of occurrences statistics to be an array of values:

<?php

$things = ['apple', 'apple', 'banana', 'tree', 'tree', 'tree'];
$values = array_count_values($things);

print_r($values);

// Array
// (
//     [apple] => 2
//     [banana] => 1
//     [tree] => 3
// )

Build the array

Given the need to generate an array of fixed-length value, may be used  array_fill ()  function:

<?php
$bind = array_fill(0, 5, '?');
print_r($bind);

The scope create an array, such as hours or letters, may be used  range ()  function:

<?php
$letters = range('a', 'z');
print_r($letters); // ['a', 'b', ..., 'z']

$hours = range(0, 23);
print_r($hours); // [0, 1, 2, ..., 23]

To achieve the acquired part of the element in the array - for example, obtaining the first three elements - used  array_slice ()  function:

<?php
$numbers = range(1, 10);
$top = array_slice($numbers, 0, 3);

print_r($top);// [1, 2, 3]

Sorting an array

First, keep in mind about sorting function in PHP are  referenced by value  , sorted successful return  true  sorted failed to return  false . Basic function is the sort of  sort ()  function, which results after the execution of the sort does not preserve the original order of the index. Sort function can be classified into the following categories:

  • a  maintain index association to sort
  • k  according to the sort keys
  • r  of the array in reverse order
  • u  user-defined Collation

You can see these sort function from the following table:

  a k r in
a asort   arsort uasort
k   ksort krsort  
r arsort krsort rsort  
in uasort     usort

Array function using a combination of

Art array processing functions using a combination of these arrays. Here We  array_filter ()  and  array_map ()  function only one line of code to complete intercepted and null characters to control the process:

<?php
$values = ['say', '  bye', '', ' to', ' spaces  ', '    '];
$words = array_filter(array_map('trim', $values));

print_r($words);// ['say', 'bye', 'to', 'spaces']

Id array creation model and data dictionary based on title, we can combine  array_combine ()  and  array_column ()  function:

<?php
$models = [$model, $model, $model];

$id_to_title = array_combine(
    array_column($models, 'id'),
    array_column($models, 'title')
);

print_r($id_to_title);

Annotation: Provides a  version that can be run .

In order to achieve the highest frequency array element acquisition occurs, we can use  array_count_values () , arsort ()  and  array_slice ()  these functions:

<?php

$letters = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd'];

$values = array_count_values($letters);
arsort($values);
$top = array_slice($values, 0, 3);

print_r($top);

It can easily pass  array_sum ()  and  array_map ()  function only calculate the number of rows to complete the order of price:

<?php
$order = [
    ['product_id' => 1, 'price' => 99, 'count' => 1],
    ['product_id' => 2, 'price' => 50, 'count' => 2],
    ['product_id' => 2, 'price' => 17, 'count' => 3],
];

$sum = array_sum(array_map(function ($product_row) {
    return $product_row['price'] * $product_row['count'];
}, $order));

print_r($sum);// 250
Published 115 original articles · won praise 101 · views 370 000 +

Guess you like

Origin blog.csdn.net/Alen_xiaoxin/article/details/105317782