


How to count the number of occurrences of a specific subscript in a 2D array in PHP?
Efficiently count the number of occurrences of specific subscript values in PHP two-dimensional arrays
This article introduces an efficient method to count the number of occurrences of a specific subscript value in a PHP two-dimensional array. Suppose we have a two-dimensional array, each subarray contains three key-value pairs, id
, name
and age
, and we need to count the number of elements with age
value of 18.
Here is an example two-dimensional array:
$array = [ ['id' => 1, 'name' => 'A', 'age' => 19], ['id' => 2, 'name' => 'B', 'age' => 20], ['id' => 3, 'name' => 'C', 'age' => 18], ['id' => 5, 'name' => 'D', 'age' => 18], ['id' => 6, 'name' => 'E', 'age' => 18] ];
We can use the array_reduce
function to implement statistics concisely:
$count = array_reduce($array, function ($carry, $item) { return $item['age'] === 18 ? $carry : $carry; }, 0); echo "There are {$count} elements with age of 18."; // Output: There are 3 elements with age of 18.
The array_reduce
function passes each element in the array $array
to the anonymous function in turn. The anonymous function checks whether age
is equal to 18, and if so, the accumulator $carry
is added to 1; otherwise, $carry
remains unchanged. The initial value is 0. Finally, array_reduce
returns the value of the accumulator, that is, the number of elements with age
of 18.
This approach is simpler and more efficient than using foreach
loops, especially when dealing with large arrays, with more obvious performance advantages. You can modify $item['age'] === 18
part to count the values of other subscripts as needed. For example, to count the number of elements with id
3, just modify the part to $item['id'] === 3
.
The above is the detailed content of How to count the number of occurrences of a specific subscript in a 2D array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Building a Hadoop Distributed File System (HDFS) on a CentOS system requires multiple steps. This article provides a brief configuration guide. 1. Prepare to install JDK in the early stage: Install JavaDevelopmentKit (JDK) on all nodes, and the version must be compatible with Hadoop. The installation package can be downloaded from the Oracle official website. Environment variable configuration: Edit /etc/profile file, set Java and Hadoop environment variables, so that the system can find the installation path of JDK and Hadoop. 2. Security configuration: SSH password-free login to generate SSH key: Use the ssh-keygen command on each node

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

Use the JSON Viewer plug-in in Notepad to easily format JSON files: Open a JSON file. Install and enable the JSON Viewer plug-in. Go to "Plugins" > "JSON Viewer" > "Format JSON". Customize indentation, branching, and sorting settings. Apply formatting to improve readability and understanding, thus simplifying processing and editing of JSON data.

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Troubleshooting HDFS configuration errors under CentOS Systems This article is intended to help you solve problems encountered when configuring HDFS in CentOS systems. Please follow the following steps to troubleshoot: Java environment verification: Confirm that the JAVA_HOME environment variable is set correctly. Add the following in the /etc/profile or ~/.bashrc file: exportJAVA_HOME=/path/to/your/javaexportPATH=$JAVA_HOME/bin: $PATHExecute source/etc/profile or source~/.bashrc to make the configuration take effect. Hadoop

When configuring Hadoop Distributed File System (HDFS) on CentOS, the following key configuration files need to be modified: core-site.xml: fs.defaultFS: Specifies the default file system address of HDFS, such as hdfs://localhost:9000. hadoop.tmp.dir: Specifies the storage directory for Hadoop temporary files. hadoop.proxyuser.root.hosts and hadoop.proxyuser.ro

The Installation, Configuration and Optimization Guide for HDFS File System under CentOS System This article will guide you how to install, configure and optimize Hadoop Distributed File System (HDFS) on CentOS System. HDFS installation and configuration Java environment installation: First, make sure that the appropriate Java environment is installed. Edit /etc/profile file, add the following, and replace /usr/lib/java-1.8.0/jdk1.8.0_144 with your actual Java installation path: exportJAVA_HOME=/usr/lib/java-1.8.0/jdk1.8.0_144exportPATH=$J
