Home > Backend Development > PHP Problem > How to filter php array by fields

How to filter php array by fields

Release: 2023-02-28 06:52:01
Original
5763 people have browsed it

How to filter php array by fields

How to filter PHP arrays by fields:

1. Use foreach to traverse the array to filter data

foreach is often used in PHP to traverse arrays, and then process the elements in the array. Below, foreach is used to traverse the $arr array, and filter the content of the elements with the field con in the array to filter out no less than 200, and an array not larger than 500.

The code is as follows:

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

2. Use the for loop to traverse the array to filter data

The for loop is also commonly used in PHP. It is mainly used to execute the specified code block in a loop until the conditions are not met to terminate execution. The following code implements filtering out arrays greater than 400 according to the con field and placing them into a new array $newarr.

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

3. Use the array_filter function to implement the array by field Filter data

The array_filter function uses the callback function method to filter the values ​​in the array to filter out the required data. The following code implements filtering out arrays smaller than 300 and placing them into a new array $newarr.

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

4. How to use a while loop to traverse the array Filter data

The while loop will execute the specified code block cyclically as long as the conditions are met. The following code implements filtering out arrays less than 500 according to the con field and placing them into a new array $newarr.

How to filter php array by fields

The result after running the above code is as follows:

How to filter php array by fields

Recommended: php server

The above is the detailed content of How to filter php array by fields. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template