0

On a page where I compare questionnaires, I calculate the average for both. However, a certain line of code always ends in a division by zero no matter what numbers I input. The code:

<?php foreach($questions as $question) : ?>
    <?= Html::tag('h4', $question->question) ?>
    <?php
    //FIRST SET OF QUESTIONNAIRES
    $answers1 = $questionnaires1->andWhere(['id_question' => $question->id]);
    $all1 = [];
    foreach($answers1->orderBy(['answer' => SORT_ASC])->all() as $answer1){
        $all1[] = $answer1->answer;
    }
    $array1 = [
        Yii::t('app', 'Number of answers') => $answers1->count(),
        Yii::t('app', 'Average answer') => round(array_sum($all1)/count($all1), 2),
        Yii::t('app', 'Median') => calculate_median($all1),
        Yii::t('app', 'Standard deviation') => round(sd($all1), 2)
    ];

First I store each individual answer in an array and order it by ascending numbers. I then calculate the average by adding each value in the array, deviding it by the number of records in the array. I also round the result to 2 decimals.

For some reason, round(array_sum($all1)/count($all1), 2) always results in a devision by zero. I checked both values before performing the calculation for i.e. 4/3. It should obviously result in 1.3333333.

Lastly, when I try echo var_dump(round(array_sum($all1)/count($all1), 2)) it returns float(1.33) as expected... Maybe I am overlooking something very simple here, but I don't see it.

NullError
  • 71
  • 2
  • 11
  • Just a thought!!! how many questions are you looping through. I think your model for one of the question is returning empty, Hence `count($all1)` returns 0. – Think Different Jul 15 '16 at 14:47
  • So, just to be clear, you're saying that `round(array_sum($all1)/count($all1), 2)` gives you an error, but `var_dump(round(array_sum($all1)/count($all1), 2))` doesn't?? – Patrick Q Jul 15 '16 at 14:49
  • You're doing this inside nested foreach loops. If you do the count() check after both loops finish, you'll only ever see the count for the final array processsed. That means some intermediate array COULD be empty. you need to do your count() debug checking inside the loop, right where you do the division. – Marc B Jul 15 '16 at 14:51
  • Do a `if (count($all1) == 0) { var_dump(...output here...);die();}` etc right before `$array1 = []` – chris--- Jul 15 '16 at 15:09

0 Answers0