Home Backend Development PHP Tutorial How to count the number of specific key-value pairs in a PHP 2D array?

How to count the number of specific key-value pairs in a PHP 2D array?

Apr 01, 2025 pm 12:39 PM
key value pair red

Detailed explanation of the method of efficiently counting the number of specific key-value pairs in PHP two-dimensional arrays

This article will introduce how to efficiently count the number of specific key-value pairs in a PHP two-dimensional array. Suppose you have a two-dimensional array that needs to count the number of elements in which a specific key's value is equal to a specific value.

How to count the number of specific key-value pairs in a PHP 2D array?

Question description:

Given a PHP two-dimensional array, for example:

 $arr = array(
    array('id' => 1, 'name' => 'A', 'age' => 19),
    array('id' => 2, 'name' => 'B', 'age' => 20),
    array('id' => 3, 'name' => 'C', 'age' => 18),
    array('id' => 5, 'name' => 'D', 'age' => 18),
    array('id' => 6, 'name' => 'E', 'age' => 19)
);
Copy after login

We need to count the number of elements with age value of 18.

Solution:

You can loop through the array using foreach and count using conditional statements:

 $arr = array(
    array('id' => 1, 'name' => 'A', 'age' => 19),
    array('id' => 2, 'name' => 'B', 'age' => 20),
    array('id' => 3, 'name' => 'C', 'age' => 18),
    array('id' => 5, 'name' => 'D', 'age' => 18),
    array('id' => 6, 'name' => 'E', 'age' => 19)
);

$count = 0;
foreach ($arr as $item) {
    if (isset($item['age']) && $item['age'] == 18) {
        $count ;
    }
}

echo "Number of elements with Age of 18: " . $count; // Output: Number of elements with Age of 18: 2
Copy after login

This code first initializes the counter $count to 0. It then iterates over each element in the array. isset($item['age']) checks whether age key exists to avoid errors with undefined indexes. If the age key exists and the value is 18, the counter $count is incremented by 1. Finally, it outputs statistics.

More advanced solutions (using array_filter and count ):

For more complex statistical requirements, you can use array_filter function and count function combination:

 $arr = array(
    array('id' => 1, 'name' => 'A', 'age' => 19),
    array('id' => 2, 'name' => 'B', 'age' => 20),
    array('id' => 3, 'name' => 'C', 'age' => 18),
    array('id' => 5, 'name' => 'D', 'age' => 18),
    array('id' => 6, 'name' => 'E', 'age' => 19)
);

$filtered = array_filter($arr, function ($item) {
    return isset($item['age']) && $item['age'] == 18;
});

$count = count($filtered);

echo "Number of elements with Age of 18: " . $count; // Output: Number of elements with Age of 18: 2
Copy after login

The array_filter function uses an anonymous function as a callback to filter out elements that meet the conditions ( age value is 18). The count function directly calculates the number of elements in the filtered array. This method is simpler and has better readability. Which method to choose depends on your personal preferences and code style, and both methods can achieve the same effect.

The above is the detailed content of How to count the number of specific key-value pairs in a PHP 2D array?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How Debian improves Hadoop data processing speed How Debian improves Hadoop data processing speed Apr 13, 2025 am 11:54 AM

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

What steps are required to configure CentOS in HDFS What steps are required to configure CentOS in HDFS Apr 14, 2025 pm 06:42 PM

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

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

How to format json in notepad How to format json in notepad Apr 16, 2025 pm 07:48 PM

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.

What files do you need to modify in HDFS configuration CentOS? What files do you need to modify in HDFS configuration CentOS? Apr 14, 2025 pm 07:27 PM

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

What is the execution process of Debian Hadoop What is the execution process of Debian Hadoop Apr 13, 2025 am 11:24 AM

The Hadoop task execution process mainly includes the following steps: Submit the job: the user uses the command line tools or API provided by Hadoop on the client machine to build the task execution environment and submit the task to YARN (Hadoop's resource manager). Resource application: After YARN receives the task submission request, it will apply for resources from the nodes in the cluster based on the resources required by the task (such as memory, CPU, etc.). Task Start: Once the resource allocation is completed, YARN will send the task's startup command to the corresponding node. On the node, NodeMana

TigerVNC share file method on Debian TigerVNC share file method on Debian Apr 13, 2025 am 11:45 AM

This article describes how to use TigerVNC to share files on Debian systems. You need to install the TigerVNC server first and then configure it. 1. Install the TigerVNC server and open the terminal. Update the software package list: sudoaptupdate to install TigerVNC server: sudoaptinstalltigervnc-standalone-servertigervnc-common 2. Configure TigerVNC server to set VNC server password: vncpasswd Start VNC server: vncserver:1-localhostno

See all articles