0

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

1
  • Please remember to select an answer. : ) Commented Sep 15, 2016 at 3:12

2 Answers 2

5
for ($i = 1; $i <= 12; $i++) {
    if(in_array($i, $month)){
      echo "$i" . "\n";
    }else {
      echo "0" . "\n";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.