Indefinite array key

Asked

Viewed 158 times

-1

Community greetings, I’m starting in php and came across a problem that I believe is about variable scope.

The project is to show the prime divisors of a number (saved in the "divisors" array) and the results of the divisions (saved in the "Results array").

The error I find is that I can’t use the "$i" index inside while and for.

When running the code, the two errors I receive refer to the snippet "if($GLOBALS['num'] % $GLOBALS['primos[$i]'] == 0){".The mistakes are:

Warning: Undefined array key 25 in C: xampp htdocs TESTES calculadora.php on line 17

Fatal error: Uncaught Divisionbyzeroerror: Modulo by zero in C: xampp htdocs TESTES calculadora.php:17 Stack trace: #0 {main} thrown in C: xampp htdocs TESTES calculadora.php on line 17

  $primos = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 
  89, 97);
  

  $num = $_POST["number"];
  $divisors = array();
  $results = array();

  echo "O número é $num";
  
  for($i = 0; $i <= count($primos); $i++){

    $p_nums = $GLOBALS['primos'];
    $i_atual = $i;

    if($GLOBALS['num'] % $GLOBALS['primos[$i]'] == 0){
      $GLOBALS['divisors'][] = $GLOBALS['primos[$i]'];

      $GLOBALS['num'] /= $GLOBALS['primos[$i]'];
      $GLOBALS['results'][] = $GLOBALS['num'];

      while($GLOBALS['num'] % $GLOBALS['primos[$i]'] == 0){
        $GLOBALS['num'] /= $GLOBALS['primos[$i]'];
        $GLOBALS['results'][] = $GLOBALS['num'];
      }
    }  
  }

1 answer

1


The problem you are encountering is because you told your code to count the amount of items in the array and do it this amount of times. It has 25 values in the array so it tries to do from 0 to 25 (giving 26x). You cannot fix this by changing the start because the positions of the array start at 0 so you have to have it do the until value less than the number of items in the array, it will run from 0 to 24, which also gives 25x, but starting from 0:

for($i = 0; $i < count($primos); $i++)
  • Another thing too, which is not part of the question, is that you use all the time $GLOBALS['primos[$i]'], but inside the for you define $p_nums = $GLOBALS['primes']; then you wouldn’t need to use the global variable inside the for, since you already copied the data inside...

  • 1

    Thank you so much, I fixed it|!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.