-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'];
}
}
}
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...
– Leticia Rosa
Thank you so much, I fixed it|!
– Angelo Schuler Piletti