Reputation:
<?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.
Upvotes: 0
Views: 4854
Reputation: 7617
<?php
function iterate($x){ //this is the function
for ($i = 0; $i < 10; $i++){ //this is the loop procedure to iterate 10 times
echo "{$x}<br/>"
}
}
$y = "xyz"; //variable declaration
echo iterate($y); //should be iterate xyz as much 10 times.
Upvotes: -2
Reputation: 1189
looks like you are confused on what you are doing.
You are printing the $i which is used for iteration not the one you passed (i,e. $x
)
to fix this,
you should echo $x
which is the one you want to print
<?php
function iterate($x){ //this is the function
for ($i = 0; $i <= 10; $i++){ //this is the loop procedure to iterate 10 times
echo $x; //it will show 0123456789 on the screen
}
}
?>
now that the logic is fixed, there still some problem here you are printing the function whose role is to print the xyz.
<?php
$y = "xyz"; //variable declaration
iterate($y); //should be iterate xyz as much 10 times.
?>
combining both solution:
<?php
function iterate($x){ //this is the function
for ($i = 0; $i <= 10; $i++){ //this is the loop procedure to iterate 10 times
echo $x; //it will show 0123456789 on the screen
}
}
$y = "xyz"; //variable declaration
iterate($y); //should be iterate xyz as much 10 times.
?>
Upvotes: 0
Reputation: 7
If i well understand your question
for ($i = 0; $i <= 10; $i++){
echo $y; //instead of xyz
}
Upvotes: -1
Reputation: 34416
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.
Upvotes: 4