Search code examples
phpcounting

PHP count the number of occurances of values of a variable


This has to do with counting in PHP, and there are numerous questions and examples of that, but none that I can find of what I need to do: count the occurrences of the value of a variable and output that count as its own variable.

The values I want to count and output as variables are each of the 50 state two letter abbreviations, i.e. AL, AK AR...; they are contained in $state.

What's the most efficient way to count the number of occurrences of each state and output each as a variable, i.e. $AL_total and $AK_total and $AR_total, etc.?

// I have data in the format
// firstname\n lastname \naddress \ncity \nstate \nzip
// This explode strings into array
foreach($values as $val) {
$valuearray = explode("\n", implode($val));

// This assigns variables that are used to echo each field of data
$firstname = $valuearray[0];
$lastname = $valuearray[1];
$address = $valuearray[2];
$city = $valuearray[3];
$state = $valuearray[4];
$zip = $valuearray[5];

// count $state and output as $AL_total , $AK_total , $AR_total , etc.


// And then...

echo $AL_total;

etc....

Solution

  • This could be an aproach based in your initial requirements:

    #inside the loop
    
    $states[$state] = null;
    
    if (!isset(${$state . '_total'})) {
        ${$state . '_total'} = 1;
    } else {
        ${$state . '_total'} += 1;
    }
    

    And then:

    #after the loop
    foreach ($states as $state => $_null) {
        echo "Total ".$state." = ".${$state . '_total'}."\n";
    }
    

    And if you want to ouput a specific state that you know it:

    #after the loop
    echo "Total AL = ".((isset($AL_total)) ? $AL_total : 0);
    

    You can see it runing here


    And if you prefer to get a single array using array_count_values() function (as commented by @nice_dev) the do the following:

    #inside the loop
    $states_count[] = $state;
    

    And then:

    #after the loop
    $count_by_state = array_count_values($states_count);
    print_r($count_by_state);
    echo "Total AL = ".(isset($count_by_state['AL']) ? $count_by_state['AL'] : 0);
    

    will output something like this:

    Array
    (
        [AN] => 1
        [AK] => 5
        [AR] => 5
        [AL] => 4
    )
    Total AL = 4
    

    You can see it running here