Home > Software design >  PHP: Do I need nested foreach loops or multiple arrays?
PHP: Do I need nested foreach loops or multiple arrays?

Time:12-23

I'm not sure of the terminology to describe what I need to do. Two nested foreach loops? Multiple arrays? A multi-dimensional array?

I am counting the total number of occurrences of each state (AK, AL, AR, etc)

$states_count[] = $state;
$count_by_state = array_count_values($states_count);

And var_dump($count_by_state) gives me

["AK"]=> int(3) ["AL"]=> int(6) ["AR"]=> int(4) ["AZ"]=> int(9) ["CA"]=> int(98) ["CO"]=> int(44) ....

So the Alaska total is 3, the Alabama total is 6, etc.

In separate code, I use this foreach to build a menu:

<?php $states = array('AK'=>'Alaska', 'AL'=>'Alabama'....  );

foreach ($states as $key => $value) {
echo $key; echo $value; echo ',';
} 

which outputs AK Alaska, AL Alabama, AR Arkansas,...

But how do I get this to work?

foreach ($states as $key => $value) {
echo $key; echo $value; echo $each-individual-state-count-total from $count_by_state)

CodePudding user response:

You can use the key of your foreach loop to index into the $count_by_state array (and possibly check if the key exists first)

$count_by_state = [
    "AK" => 3,
    "AL" => 6,
    "XXX" => 9
];
$states = array('AK' => 'Alaska', 'AL' => 'Alabama');

foreach ($states as $key => $value) {
    if (array_key_exists($key, $count_by_state)) {
        echo $value . "," . $count_by_state[$key] . PHP_EOL;
    }
} 

Output

Alaska,3
Alabama,6
  • Related