简体   繁体   中英

How to get numer of repeating elements in PHP array?

Sometimes we need to get only the count of repeating elements from an array, or the count of each elements in an array

    $array = array(123, 'abc', 26, 'swat', 1, 'swat', 83);

I would like to print:

    123 (1)
    abc (1)
    26 (1)
    swat (2)
    1 (1)
    83 (1)

use php function array_count_values

<?php
    $array = array(123, 'abc', 26, 'swat', 1, 'swat', 83);
    print_r(array_count_values($array));
?>

The output is:

Array
(
    [123] => 1
    [abc] => 1
    [26] => 1
    [swat] => 2
    [1] => 1
    [83] => 1
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM