0

Have a 'function use' lesson problem. The code inside the function (when it's put outside the function; returns an array) seems correct, but the function outputs NULL. Here's what it looks. Point where I'm doing wrong, please.

function getDivisors($num)
       {
         for ($i=1; $i<=$num; $i++)
           {
             if ($num % $i == 0)
               {
                 $divisors[] = $i;
               }
           }
        }

I suppose the output to the array is an incorrect, but... that's still unsure.

3
  • 3
    Looks like you forgot to return the array from the function Commented Sep 30, 2021 at 13:55
  • P.s. show us how you're calling the function, for context Commented Sep 30, 2021 at 14:15
  • Thank you very much! The function is a part of an exercise, which demands the use of it in function getCommonDivisors($num1,$num2) like this: $result[] = array_intersect(getDivisors($num1), getDivisors($num2)); So the whole thing breaks out with NULL as the variables. Commented Oct 1, 2021 at 5:41

1 Answer 1

1

Your function returns null because you didn't return your array.

Modify your function like this :

function getDivisors($num) {
  for ($i=1; $i<=$num; $i++) {
     if ($num % $i == 0) {
        $divisors[] = $i;
     }
  }
  return $divisors;
}
Sign up to request clarification or add additional context in comments.

1 Comment

My great thanks. The topic appeared to have lots of pitfalls for me.

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.