Home  >  Article  >  Backend Development  >  How to count the number of the same value in an array in php

How to count the number of the same value in an array in php

青灯夜游
青灯夜游Original
2022-04-19 20:26:352581browse

In PHP, you can use the array_count_values() function to count the number of the same value in an array. The syntax is "array_count_values($array)"; this function will return an associative array with the key name of its element. is the value of the original array, and the key value is the number of times the value appears in the original array.

How to count the number of the same value in an array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, you can use the array_count_values() function To count the number of the same value in the array, that is, the number of occurrences of the same value.

array_count_values() function is used to count the number of occurrences of all values ​​in an array. The syntax format is:

array_count_values($array)

array_count_values() function will return an associative array whose key names of elements are those of the original array. Value, the key value is the number of times the value appears in the original array.

Example:

<?php
header("Content-Type: text/html;charset=utf-8");    //设置字符编码
$array = array(7,"hello",7,8,"world",9,10,10,"hello",10);
$frequency = array_count_values($array);   // 统计数组中所有值出现的次数
echo "每个元素对应的出现次数:";
var_dump($frequency);
?>

How to count the number of the same value in an array in php

Extended knowledge: Use the array_count_values() function to find the highest repetition rate in the array Value

Just need to find out the number of occurrences of the element, and then reorder it to find the maximum key value

<?php
header("Content-Type: text/html;charset=utf-8");    //设置字符编码
$array = array(7,"hello",7,8,"world",9,10,10,"hello",10);
$frequency = array_count_values($array);   // 统计数组中所有值出现的次数
echo "每个元素对应的出现次数:";
var_dump($frequency);
echo "按照键值进行降序排序:";
arsort($frequency); // 按照键值对数组进行降序排序
var_dump($frequency);
$max_number = reset($frequency);//出现最多的次数值
$more_value = key($frequency);//出现次数最多的值
echo "数组中出现次数最多的值为:{$more_value},总共出现{$max_number}次";
?>

How to count the number of the same value in an array in php

Recommended learning: "PHP video tutorial

The above is the detailed content of How to count the number of the same value 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