Jump to content

Archived

This topic is now archived and is closed to further replies.

Hellusius

Noob php question

Recommended Posts

I know this has no real relevance, but I would like to ask why this does not work.
I wanted to echo each number from 0 to 20

[code]<?php
function hello ($amount=25)
{
  for ($i = 0; $i < $amount; $i++)
  return $i;
}
?>

<?php
echo (hello($i));
?>[/code]

Share this post


Link to post
Share on other sites
return halts excecution of a function and returns the specified value, so:

[code=php:0]

function foo()
{
    echo 'a';
    return false;
    echo 'b';
}

foo();
[/code]

would simpyl echo 'a', as once the function returns, the rest of the code within it is not executed.
You could assign the value of $i to a variable, like so:

[code=php:0]
$string = $string . ' ' . $i;
[/code]
(.= is equivilent to $string = $string . $i)

And then return $string.

Share this post


Link to post
Share on other sites
well, I just wanted to echo the number 0 to 20 since the function has to play itself from 0 to 20 right, so I thought, if'd take varb "i" I would be safe

Share this post


Link to post
Share on other sites
[code=php:0]
function hello ($amount=20)
{
  for ($i = 0; $i <= $amount; $i++)
  echo $i . "<br />\n";
}
?>

$i = 20;
hello($i);

[/code]


Why not just have the function output it to the screen?

Share this post


Link to post
Share on other sites
didn't think of that one, thanks for the header, and

[code]function hello ($amount=20)
{
  for ($i = 0; $i <= $amount; $i++)
  echo $i . "<br />\n";
}
?>

<?php
hello();
?>
[/code]

is shorter ^_^

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.