PHP Division by zero, but returns 1.33

208 Views Asked by At

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.

0

There are 0 best solutions below