0

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....
2
  • array_count_values() ? Commented Dec 15, 2021 at 19:07
  • 1
    aha, I think that's what I need :) Commented Dec 15, 2021 at 19:19

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, that's interesting and it works. nice_dev pointed out the possible use of array_count_values(). Would that be easier?
@BlueDogRanch: It depends of how do you want to manage them. First I did it in the way you were asking for in your inital post. Now I have added the array_count_values() function that will generate an array with all values that you could access via $count_by_state[state] instead $state_total vars. As you wish. Surely the array_count_values() solution looks better and cleaner than the other.
Thanks! Using array_count_values works better for me; the first example killed my loop for some reason. And it appears to be more efficient.
Ah, Warning: Undefined array key "AL" when AL is 0, I guess. Do we need to check if a key exists when we echo "Total AL = ".$count_by_state['AL']; ?
@BlueDogRanch: I have edited my answer and added the array verification. Also updated the link to test it again.
|
0

I would recommend using an associative array where the keys are the states and the values are the counts, e.g.:

# before your loop:
$stateCount = [];

# in your loop:
if( ! isset( $stateCount[$state] ) ) { # first time $state is seen, init to 1
    $stateCount[$state] = 1;
} else {
    $stateCount[$state]++;
}

4 Comments

nice_dev pointed out the possible use of array_count_values(). Would that be easier?
imo, your array for counting would be unnecessarily large (and use up more memory) with using array_count_values
That's interesting. How do I output the total for i.e., AL? Is that echo $al?
I recommend reading up on how associative arrays work in PHP: php.net/manual/en/language.types.array.php. To access AL, you would use echo $stateCount['AL'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.