0

I have the following code:

$chart_data = array();
foreach ($range as $range_day) {
  foreach ($numbers as $number) {
    if($range_day == $number['date']){
      @$chart_data[$range_day] += $number['events'];
    } else {
      if(isset($chart_data[$range_day])){
        $chart_data[$range_day] += 0;
      }
    }
  }
}

This line: $chart_data[$range_day] += 0; was giving me an undefined index error, so I added the isset check, but it's not set so it wrecks my array. I know that it's not set, and I don't care, but I read all over that the @ solution is in poor taste. How can I remove the error the correct way?

3 Answers 3

1

You could just set it to zero at the beginning:

$chart_data = array();
foreach ($range as $range_day) {
  $chart_data[$range_day] = 0;
  foreach ($numbers as $number) {
    if($range_day == $number['date']){
      $chart_data[$range_day] += $number['events'];
    } else {
      if(isset($chart_data[$range_day])){
        $chart_data[$range_day] += 0;
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Would recommend also removing error suppression, since it is no longer "necessary" once you add the isset() check.
1

Did you take a look at the array_key_exists function: http://php.net/manual/en/function.array-key-exists.php ?

Something like:

$chart_data = array();
foreach ($range as $range_day) {
  foreach ($numbers as $number) {
    if(!array_key_exists($range_day, $array)) {
      $chart_data[$range_day] = 0;
    }
    if($range_day == $number['date']){
      $chart_data[$range_day] += $number['events'];
    }
  }
}

1 Comment

Would recommend also removing error suppression, since it's no longer "necessary" once you add the array_key_exists() check.
1

You can check if it's not set, then set it:

foreach ($numbers as $number) {
    if (!isset($chart_data[$range_day])) {
        $chart_data[$range_day] = 0;
    }
    if ($range_day == $number['date']) {
        $chart_data[$range_day] += $number['events'];
    } else {
        $chart_data[$range_day] += 0; // you're just adding 0 so why have this line at all?
    }
}

This answers assumes that there is the possibility that $range could contain a duplicate $range_day and so it won't overwrite the corresponding element in $chart_data.

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.