Jump to content


Photo

Noob php question


  • Please log in to reply
4 replies to this topic

#1 Hellusius

Hellusius
  • Members
  • PipPipPip
  • Advanced Member
  • 55 posts

Posted 03 September 2006 - 06:45 AM

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

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

<?php
echo (hello($i));
?>


#2 Joe Haley

Joe Haley
  • Members
  • PipPipPip
  • Advanced Member
  • 103 posts
  • LocationCanada, eh?

Posted 03 September 2006 - 08:05 AM

return halts excecution of a function and returns the specified value, so:


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

foo();

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:

$string = $string . ' ' . $i;
(.= is equivilent to $string = $string . $i)

And then return $string.
Give a man a fish; you have fed him for today.  Teach a man to fish; and you have fed him for a lifetime
Don't teach men to program. Teach them to fish.

Please, try the RTFM solution before asking for help:
http://php.net/manual/en/index.php

#3 Hellusius

Hellusius
  • Members
  • PipPipPip
  • Advanced Member
  • 55 posts

Posted 03 September 2006 - 08:09 AM

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

#4 extrovertive

extrovertive
  • Members
  • PipPipPip
  • Advanced Member
  • 235 posts

Posted 03 September 2006 - 08:12 AM

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

$i = 20;
hello($i);



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

#5 Hellusius

Hellusius
  • Members
  • PipPipPip
  • Advanced Member
  • 55 posts

Posted 03 September 2006 - 08:26 AM

didn't think of that one, thanks for the header, and

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

<?php
hello();
?>

is shorter ^_^




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users