mogleng mogleng - 1 month ago 6
PHP Question

how to use for loop inside php function

<?php
function iterate($x){ //this is the function
for ($i = 0; $i <= 10; $i++){ //this is the loop procedure to iterate 10 times
echo $i; //it will show 0123456789 on the screen
}
}

$y = "xyz"; //variable declaration
echo iterate($y); //should be iterate xyz as much 10 times.
?>


wish to echo(print) xyz ten times using for loop inside the php function, the result not as expected.
how to show the xyz iterate ten times.

Answer

echo $x; which is the value you pass to the function. You do not have to echo the function because echo is called inside the function. You also need to change your counter. 0 to 9 is 10 times, or 1 to 10.

function iterate($x){ //this is the function
        for ($i = 0; $i <= 9; $i++){ //this is the loop procedure to iterate 10 times
            echo $x; //it will show xyz on the screen, 10 times
        } 
    }

    $y = "xyz"; //variable declaration
    iterate($y); //should be iterate xyz as much 10 times. 

EXAMPLE