So I tried making function with nested loop and if in it but somehow when I try to open the file it doesn't show anything.. here's my codes
<?php
$result[0] = "no";
$condition[0] = "yes";
function cek() {
for ($i=0; $i<2; $i++) {
if ($result[$i] == "no") {
for ($i=0; $i<2; $i++) {
if ($condition[$i] == "yes") {
echo ("means yes");
break;
}
else {
echo ("means no");
break;
}
}
}
}
}
cek();
?>
any help will be appreciated. thank you
Here is the result of the execution of your code :
$ php test.php
PHP Notice: Undefined variable: result in /home/.../test.php on line [...]
PHP Notice: Undefined variable: result in /home/.../test.php on line [...]
The line concern is :
if ($result[$i] == "no")
Variables $result
and $condition
are undefined in your function, you must either pass as an argument to your function or use global (which should be avoided for this case).
Moreover, this loop will also fail :
for ($i=0; $i<2; $i++)
Indeed, "2" isn't the size of $condition
(or $result
). You could use sizeof($condition)
or count($condition)
instead.
And finally, you shouldn't use the same increment ($i
) in your both nested loops.
This code will work :
<?php
$result = array("no");
$condition = array("yes");
function cek(array $result, array $condition) {
for ($i=0; $i<sizeof($result); $i++) {
if ($result[$i] == "no") {
for ($j=0; $j<sizeof($condition); $j++) {
echo "means " . (($condition[$i] == "yes") ? "yes" : "no");
break;
}
}
}
}
cek($result, $condition);
But I'm not sure that's exactly what you're looking to do ;)