Ask Your Question
0

How can PHP determine if there are duplicate values in an array and also provide a count for each occurrence?

asked 2022-09-03 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-31 10:00:00 +0000

david gravatar image

To determine if there are duplicate values in an array and provide a count for each occurrence, you can use the PHP built-in function "arraycountvalues()". This function takes an array as a parameter and returns an associative array where the keys are the unique values from the original array, and the values are the number of occurrences of each value. Here's an example code:

$array = array("apple", "banana", "apple", "orange", "banana", "grape");
$counted_array = array_count_values($array);
foreach ($counted_array as $key => $value) {
    if ($value > 1) {
        echo "$key appears $value times\n";
    } else {
        echo "$key appears $value time\n";
    }
}

This code will output:

apple appears 2 times
banana appears 2 times
orange appears 1 time
grape appears 1 time

This means that "apple" and "banana" appear twice each in the original array, while "orange" and "grape" appear only once each.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-03 11:00:00 +0000

Seen: 13 times

Last updated: May 31 '21