Count element values from a PHP array

Asked

Viewed 2,233 times

3

I got the following array, for example:

Array
(
    [0] => Array
        (
            [ID] => 401675295
            [DATA] => 2016-06-28 15:33:07
            [TITULO] => Teste
            [TEXTO] => 
            [TIPO] => 4
            [NOME] => JOAO
        )

    [1] => Array
        (
            [ID] => 401675295
            [DATA] => 2016-06-28 16:34:31
            [TITULO] => Avaliação
            [TEXTO] => 
            [TIPO] => 3
            [NOME] => VITOR
        )

    [2] => Array
        (
            [ID] => 401675295
            [DATA] => 2016-06-28 16:34:41
            [TITULO] => Atendimento
            [TEXTO] => 
            [TIPO] => 3
            [NOME] => JOAO
        )

    [3] => Array
        (
            [ID] => 401675295
            [DATA] => 2016-06-28 16:34:52
            [TITULO] => Concluido
            [TEXTO] =>
            [TIPO] => 1
            [NOME] => PAULO
        )

)

How can I count the [TYPE] by value? How to know how many [TYPE] are equal to 3, or 4 for example?

1 answer

4


It’s very simple. Use array_map to list all elements with name TIPO. Then use the function array_count_values to know the result.

$tipos = array_map(function ($value) { return $value['TIPO'];}, $array);

array_count_values($tipos);

See an example on Ideone.com

  • Did not work, showed "Undefined index: TYPE"

  • Yes, this $array = array(); and that array I put in the question.

  • Thanks, I got it, I was missing a name here. = P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.