插件窝 干货文章 PHP怎么判断数组中有几个相同值

PHP怎么判断数组中有几个相同值

数组 array apple 次数 614    来源:    2025-03-16

在PHP中,你可以使用array_count_values()函数来判断数组中每个值出现的次数。这个函数会返回一个关联数组,其中键是原数组中的值,值是该值在原数组中出现的次数。

以下是一个示例代码:

<?php
$array = array("apple", "banana", "apple", "orange", "banana", "apple");

// 使用 array_count_values 函数
$countValues = array_count_values($array);

// 输出结果
print_r($countValues);
?>

输出结果将是:

Array
(
    [apple] => 3
    [banana] => 2
    [orange] => 1
)

在这个例子中,array_count_values()函数统计了数组中每个值出现的次数,并返回了一个关联数组。你可以通过这个关联数组来获取每个值出现的次数。

如果你想获取某个特定值出现的次数,可以直接访问这个关联数组:

<?php
$array = array("apple", "banana", "apple", "orange", "banana", "apple");

// 使用 array_count_values 函数
$countValues = array_count_values($array);

// 获取 "apple" 出现的次数
$appleCount = $countValues['apple'];

echo "Apple appears $appleCount times.";
?>

输出结果将是:

Apple appears 3 times.

通过这种方式,你可以轻松地判断数组中每个值出现的次数。