Home  >  Article  >  Backend Development  >  How to determine how many times a specified value appears in an array in PHP

How to determine how many times a specified value appears in an array in PHP

青灯夜游
青灯夜游Original
2022-07-05 20:45:053493browse

Implementation steps: 1. Use the array_count_values() function to count the number of all values ​​in the array. The syntax "array_count_values ​​(original array)" will return an associative array. The key name of its element is the value of the original array. The key The value is the number of times the value appears in the original array; 2. Use the "$associative array variable name ['specified value']" statement to access the associative array and obtain the number of occurrences of the specified value.

How to determine how many times a specified value appears in an array in PHP

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

php determines the specified value Methods for how many times a specified value appears in an array

In PHP, you can use the array_count_values() function to count the number of times a specified value appears in an array.

Implementation steps:

Step 1: Use array_count_values() function to count the number of times of all values ​​in the array

array_count_values() The function counts the occurrences of all values ​​in an array.

<?php
header("Content-type:text/html;charset=utf-8");
$arr = array("A","Cat","Dog","A","Dog");
echo "原数组:";
var_dump($arr); 

echo "数组中所有元素的出现次数:";
$count = array_count_values($arr); 
var_dump($count);
?>

How to determine how many times a specified value appears in an array in PHP

It can be seen that the array_count_values() function will return an associative array, the key name of its element is the value of the original array, and the key value is the value that appears in the original array number of times.

Step 2: Get the number of occurrences of the specified value

$关联数组变量名[&#39;指定值&#39;]

This component can access the value (number of occurrences) of the corresponding key name (original array element) in the associative array

Implementation example:

<?php
header("Content-type:text/html;charset=utf-8");
$arr = array("A","Cat","Dog","A","Dog");
echo "原数组:";
var_dump($arr); 

echo "数组中所有元素的出现次数:";
$count = array_count_values($arr); 
var_dump($count);
echo "字符A 的出现次数:".$count["A"];
?>

How to determine how many times a specified value appears in an array in PHP

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to determine how many times a specified value appears in an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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