phpLoop
phpLoop

Reputation: 3

PHP for foreach

I want to check for month in one year found in $month variable, if data found show the month (in number), if not found show '0'

<?php
$month = array(
    '2',
    '3',
    '4',
    '7',
    '12'
);

for ($i = 1; $i <= 12; $i++) {
    foreach($month as $key => $value) {
        if ($value == $i) {
            echo "$i" . "\n";
        }
        else {
            echo "0" . "\n";
        }
    }
}

from code above I get

0
0
0
0
0
2
0
0
0
0
0
3
0
0
0
0
0
4
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
12

if I add break 1 after else

for ($i = 1; $i <= 12; $i++) {
    foreach($month as $key => $value) {
        if ($value == $i) {
            echo "$i" . "\n";
        }
        else {
            echo "0" . "\n";
        }
        break 1;
    }
}

I got 12 result but not what I expected.

0
2
0
0
0
0
0
0
0
0
0
0

what I want is

0
2
3
4
0
0
7
0
0
0
0
12

If I able to get that result I want to put that these result in graph using chartjs, I know how to do that. I only want to know how to get these result, any help appriciate

Upvotes: 0

Views: 53

Answers (2)

AJNeufeld
AJNeufeld

Reputation: 8695

You want to print out only once per outer loop, not once per inner loop. You want something more like:

for ($i = 1; $i <= 12; $i++) {
    $pos = 0;
    foreach($month as $key => $value) {
        if ($value == $i) {
            $pos = $i;
            break;
        }
    }
    echo "$pos" . "\n";
}

However, you can use builtin functions to do this more efficiently. See the in_array function.

Upvotes: 0

Craig
Craig

Reputation: 444

for ($i = 1; $i <= 12; $i++) {
    if(in_array($i, $month)){
      echo "$i" . "\n";
    }else {
      echo "0" . "\n";
    }
}

Upvotes: 5

Related Questions