Finding Errors in PHP Loop Code
In the following tasks, a programmer wrote some code and possibly made mistakes in it. You must check if the code does what is described. If the code works incorrectly, you must fix the errors.
The code should output numbers from 0
to 10
:
<?php
for ($i = 0; $i > 10; $i++) {
echo $i;
}
?>
The code should output numbers from 10
to 0
:
<?php
for ($i = 10; $i > 0; $i++) {
echo $i;
}
?>
The code should output numbers from 10
to 0
:
<?php
for ($i = 10; $i == 0; $i--) {
echo $i;
}
?>
The code should output numbers from 0
to 10
:
<?php
$i = 0;
while ($i >= 10) {
echo $i;
$i++;
}
?>
The code should find the sum of integers
from 1
to 10
:
<?php
$res;
for ($i = 1; $i <= 10; $i++) {
res += $i;
}
echo $res;
?>
The code should find the product of integers
from 1
to 10
:
<?php
$res = 0;
for ($i = 1; $i <= 10; $i++) {
$res *= $i;
}
echo $res;
?>
The code should square each element of the array:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
$elem = $elem ** 2;
}
var_dump($arr);
?>
The code should fill the array
with numbers from 1
to 5
:
<?php
$arr = 0;
for ($i = 1; $i <= 5; $i++) {
$arr[] = $i;
}
var_dump($arr);
?>
The code should check if the array contains
the number 3
or not:
<?php
$arr = [1, 2, 3, 4, 5];
$res = '';
foreach ($arr as $elem) {
if ($elem === 3) {
$res = '+++';
} else {
$res = '---';
}
}
echo $res;
?>
The code should output numbers
from 10
to 1
:
<?php
$i = 10;
while ($i == 10) {
echo $i;
$i--;
}
?>
The code should check if the array contains
the number 3
or not:
<?php
$arr = [1, 2, 3, 4, 5];
$res = false;
foreach ($arr as $elem) {
if ($elem === 3) {
$res = true;
break;
}
}
var_dump($res);
?>
The code should output numbers
from 10
to 1
:
<?php
$i = 10;
while ($i <= 0) {
echo $i;
$i--;
}
?>
The code should output only even elements from the array:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
if ($elem % 2 = 0) {
echo $elem;
}
}
?>
The code should output numbers
from 10
to 1
:
<?php
$i = 10;
while ($i >= 1) {
echo $i;
}
?>
The code should output numbers
from 10
to 1
:
<?php
$i = 10;
while ($i >= 1) {
echo $i;
$i++;
}
?>