


How to count the number of specific key-value pairs in a PHP 2D array?
Apr 01, 2025 pm 12:39 PMDetailed 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.
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) );
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
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
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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

Map collections in Java are powerful tools for handling key-value pairs of data. 1) Use HashMap to perform basic operations, such as storing and retrieving data, with an average time complexity of O(1). 2) Use getOrDefault method to count word frequency and avoid null value checking. 3) Use TreeMap to automatically sort key-value pairs. 4) Pay attention to the duplication of key-value pairs, and use putIfAbsent to avoid overwriting old values. 5) When optimizing HashMap performance, specify the initial capacity and load factor.

In Unity, 3D physics engines and AI behavior trees can be implemented through C#. 1. Use the Rigidbody component and AddForce method to create a scrolling ball. 2. Through behavior tree nodes such as Patrol and ChasePlayer, AI characters can be designed to patrol and chase players.

Avoiding SQL injection in PHP can be done by: 1. Use parameterized queries (PreparedStatements), as shown in the PDO example. 2. Use ORM libraries, such as Doctrine or Eloquent, to automatically handle SQL injection. 3. Verify and filter user input to prevent other attack types.

Optimizing the performance of Hadoop distributed file system (HDFS) on CentOS systems can be achieved through a variety of methods, including adjusting system kernel parameters, optimizing HDFS configuration files, and improving hardware resources. The following are detailed optimization steps and suggestions: Adjust the system kernel parameters to increase the limit on the number of files opened by a single process: Use the ulimit-n65535 command to temporarily adjust. If it needs to take effect permanently, please edit the /etc/security/limits.conf and /etc/pam.d/login files. Optimize TCP parameters: Edit /etc/sysctl.conf file, add or modify the following content: net.ipv4.tcp_tw

The garbled problem in Java Chinese is mainly caused by inconsistent character encoding. The repair method includes ensuring the consistency of the system encoding and correctly handling encoding conversion. 1.Use UTF-8 encoding uniformly from files to databases and programs. 2. Clearly specify the encoding when reading the file, such as using BufferedReader and InputStreamReader. 3. Set the database character set, such as MySQL using the ALTERDATABASE statement. 4. Set Content-Type to text/html;charset=UTF-8 in HTTP requests and responses. 5. Pay attention to encoding consistency, conversion and debugging skills to ensure the correct processing of data.

In Go, the performance problem will be triggered when the map is expanded. The following measures can be avoided: 1. Estimate the map size and set the appropriate initial capacity; 2. Process data in batches to reduce the pressure of single-scaling expansion; 3. Use sync.Map to deal with high concurrency scenarios.

For good reason, Blockdag focuses on buyer interests. Blockdag has raised an astonishing $265 million in 28 batches of its pre-sales As 2025 approaches, investors are steadily accumulating high-potential crypto projects. Whether it’s low-cost pre-sale coins that offer a lot of upside, or a blue chip network that prepares for critical upgrades, this moment provides a unique entry point. From fast scalability to flexible modular blockchain architecture, these four outstanding names have attracted attention throughout the market. Analysts and early adopters are watching closely, calling them the best crypto coins to buy short-term gains and long-term value now. 1. BlockDag (BDAG): 7 days left
