Use php array functions for functional programming and php Array Function Programming

Source: Internet
Author: User

Use php array functions for functional programming and php Array Function Programming

Because of a BUG, I found the following code in one of the corners of a project that almost collapsed.

This program is closely related to the BUG. I tried this code repeatedly and found that this code has implemented two functions.

The first is to find a record with the maximum value in the list array read from the database, and obtain the maximum value and the time related to the value.

The second is complicated. It is to map the values in the list array to another list array. This process can be considered as a JOIN operation in SQL, but the JOIN condition is very complex, I will not go into details here, and the readers do not have to go into depth.

For this piece of code, it is difficult to understand the meaning of the Code through rough observation. The light loop in the Code is set to three layers, and there are multiple complicated condition judgments, and the code format is chaotic, even the bottom line indentation of the encoding is not satisfied. Sadly, this type of code is widely used on countless Web servers around the world and runs every day.

A long time ago, I was still very young. When I saw a problem with code in the project, I felt uncomfortable and had to get rid of it. Later, I found that bad code is like a waste of oil. In the city where I live, I can touch it everywhere. Unless I don't eat, I can only close one eye, as long as there is no taste problem, you can eat it.

However, this time it is different. This code runs in the key part of a function item and cannot fully understand this Code. In the future, problems will still be stuck here. Although I understand the meaning of this code, I will forget the meaning of this Code in a few days. This is not my memory problem, but because the meaning of this Code is not clear enough.

So I restructured the code into the following, and the functions of the Code have not changed.

Do you still not understand what the code means? It doesn't matter, because the functions represented in this Code are too complex and dependent on the context of all the functions in the code, it's understandable. However, from the code structure perspective, the reconstructed code is much clearer.

I split the two functions that were originally crowded together. The above part is to calculate the maximum value, and the following part is to map the two arrays. Here I used two arrays in PHP: array_map and array_reduce. The main idea of this article is to use these functions to improve the readability of PHP code. These functions mainly include the following four functions:

Array_filter

Array_map

Array_walk

Array_reduce

These four functions are very powerful. They can completely replace loop control statements such as for, foreach, and while in terms of processing list arrays. This is also a part of functional programming in PHP.

1. array_filter Function

 

This code is easy to understand and extracts the gender field from the array as the data item of the female. The logic of the entire code is roughly as follows:

1. Define the result array to store results

2. cyclically array, perform condition judgment on each data item, and check whether the gender field is female.

3. If the conditions are met, add them to the result array.

This is the original imperative program code.

If the data in the data variable is not stored in the php array, but in the table of the relational database, how can we get the result of gender-specific data? For programmers, this seems to be a simpler problem. A single SQL statement is enough.

Obviously, using SQL to query data is more convenient and clear, and every SQL expression shows all program logic. This SQL statement only expresses: "I need gender-based data, but I don't care about how to get it." I don't know anything except the result.

We may wish to introduce this idea into PHP programming, which does not mean that the logic expression of our PHP program is clearer and the code is more readable. Fortunately, this method of Expression Programming can also be fully implemented in PHP.

Using the array_filter function, you can easily complete this task. Take a closer look at whether the original program logic is gone, including defining arrays, loops, and conditions, logically, only one gender comparison statement is left, which makes the functions implemented by the Code clear at a glance. Compared with the preceding SQL statement, the Gender judgment statement is the condition judgment after the where clause in SQL, And the array_filter function is actually the where clause in SQL. This is the embodiment of the logic of SQL statements for result-oriented programming in PHP, that is, the most popular "Declarative Programming" or "Expression Programming ".

In addition, the position of the Gender judgment statement in the Code is called a lambda expression, and the more common method is anonymous function. It is not hard to see that writing condition judgments in SQL where conditions is far less flexible than writing PHP code in anonymous functions. In the where condition, only the or and logic can be executed, php anonymous functions can be written in any way, as long as the return value of the function is a Boolean value, which is also a better place for php Declarative Programming than SQL Declarative Programming.

2. array_map Function

Let's look at an example.

The gender field in the data is Chinese and the value is also Chinese. To change both the field name and field value to English, you can use the above Code, the implementation logic is not described here.

The following describes how to implement SQL statements.

The case when statement in SQL does not seem to look good, but does not affect the expression of the overall logic. Convert this SQL statement to PHP.

Compared with the previous PHP implementation, it is much simpler and clearer.

The array_map function is used here. In SQL statements, select statements are the most commonly used. The literal meaning of select statements is "select", and select statements are also called "select query". In fact, from the perspective of relational databases, the select statement is called "projection" and is not a query. In other words, the select statement only extracts the SQL query results in a certain way (select fields, calculate values, and so on. In php, array_map expresses this layer of meaning. "ing" and "projection" are completely different expressions of meaning.

3. array_walk Function

The array_walk function has no profound significance like array_map and array_filter, but it is also indispensable in designing code with good readability.

Array_walk is an alternative function of the for or foreach statement.

The preceding Code implements the traversal of arrays by foreach and array_walk. It seems that the implementation of array_walk is more complicated, but in terms of deeper Semantics

Foreach expresses loop traversal, but there is no restriction on what to do in this loop process. delete a certain item of the array to be traversed, or modify the value of a variable other than 108,000. This is the so-called "code side effect". As the saying goes, "termite is small, causing infinite harm." When these seemingly insignificant side effects grow, it is fatal for programmers to maintain program code.

By default, the array_walk function has the scope of all code execution in the anonymous function. to depend on or operate data outside the function, you must use the use keyword of the anonymous function to import the data. Generally speaking, the permissions of the array_walk function are not as high as those of foreach. Therefore, after using the array_walk function, you cannot program as you like, however, the side effects of your code are greatly reduced, and the two sides weigh the benefits of array_walk for a reason worth using it. First, you do not need to have too many "Permissions" to write code. Second, it is self-evident to minimize the scope affected by the Code. As ZHANG Xiaolong said, the best thing we do is "restraint". Why not write code. This also applies to array_filter and array_map. Broadly speaking, all anonymous functions can enjoy this benefit.

The semantics expressed by array_walk is "If you need to use me, you 'd better not do anything except traversal, otherwise you should use native foreach"

4. array_reduce Function

Array_reduce is the set builder of the three functions mentioned above. The underlying layers of these three functions can be fully implemented by array_reduce.

Let's take a look at the php code below idea.

The common PHP code is used to calculate the average age and the maximum age in the array records. The code needs to loop through the array and store the calculation results into a scalar (a single value, differentiated from list variables ).

If Expression Programming is required to complete the compilation of these two functions, it is difficult to implement them one by one using three functions: array_filter, array_walk, and array_map.

So it's time for array_reduce to show its skills.

The above code is the implementation of Expression Programming for average age and maximum age. If you do not know the working mechanism of the array_reduce function, read the above two sections of code and think that you are reading tianshu.

This is the implementation code of the array_reduce function. The function has three parameters and the three parameters have the following functions:

The first parameter $ data is the data source to be processed.

The second parameter $ callback indicates the function that will be called during the loop. The result returned by the function will be passed in as a parameter again during the next loop call.

The third parameter $ initial is passed as the parameter when the $ callback function is called for the first time.

A recursive version of array_reduce can help you better understand the meaning of this function.

Using the array_reduce function can almost replace the vast majority of code that requires foreach, for, and while statements.

In standard functional programming languages, there are no cyclic control statements. If you want to enter cyclic computing, these functions are used for implementation, in extreme cases, if these functions cannot meet your needs, you can manually write Recursion to implement loops to achieve Expression Programming.

To sum up, why use these four functions when writing php code?

1. Through the meaning of the function itself, we can express the functions implemented by the Code, instead of pondering the specific details of the Code to understand the role of the Code.

2. Compared with imperative programming, Expression Programming can greatly simplify the implementation process of functions and improve coding efficiency.

3. Expression Programming has extraordinary significance for code readability and maintainability.

4. using anonymous functions to control code side effects

5. move from traditional process-oriented programming to modern functional programming

Supplement:

As explained in the previous example, the Code implemented using these four functions has not changed significantly compared with the traditional implementation method. However, when the problem to be solved is complicated to a certain extent, the rational use of these four functions will greatly reduce the complexity of the Code.

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.