Page 1 of 1

[solved] newbie: Return vs. Print

Posted: Tue Apr 12, 2005 4:34 am
by gen23
Hi,

can anyone please explain, in layman's term, the use of RETURN?

thanks!

Posted: Tue Apr 12, 2005 5:12 am
by CoderGoblin
How layman do you want it...

Simplistic Examples

Code: Select all

function add2numbers($num1, $num2)
{
  $retval=$num1+$num2;
  return $retval;
}

$myaddition=add2numbers(1,4);
echo($myaddition);
Would print out 5.

Going by the title of the post, return values actually return a "result" of the function which is normally saved in a variable ($myaddition in the example above). Printing/echo may be performed within the function in addition to the return. Often returns are used for error handling. If function returns 0 rather than 1 the function failed for some reason example.

Code: Select all

function isNumberValid($num)
{
  $retval=0;
  if ($num>0 and $num<=10) {
    echo("I don't know some silly text");
    $retval=1;
  }
  return $retval;
}

if (isNumberValid($_REQUEST['id']==0) {
  echo("The number you entered must be between 1 and 10 <br />");
}
Ok very simplistic examples but I hope you can get the idea.

Posted: Wed Apr 13, 2005 8:36 am
by gen23
I see... but is it okay to use Return in displaying the contents of a variable just like print/echo? or it's just simply for saying that a value is being returned?

ex.
--|
<?php |
$msg = "hello!"; |--- why isn't this block of code used/allowed?
return $msg; |
?> __|


...Sorry... I'm really in the dark here... :oops:

Posted: Wed Apr 13, 2005 9:08 am
by Chris Corbyn
gen23 wrote:I see... but is it okay to use Return in displaying the contents of a variable just like print/echo? or it's just simply for saying that a value is being returned?

ex.

<?return "hello";?> <-- why isn't this allowed?

...Sorry... I'm really in the dark here... :oops:
return is used to tell a function/process what value to send back. echo /print (aliases of each other) are used to output something to the page.

Even simpler example:

Code: Select all

$var = 'Hello World!';
echo $var;

//or this here
function mk_word() {
    return "Hello World";
}
echo mk_word();
So either way... you need to use echo /print to output the value to the page.

Posted: Wed Apr 13, 2005 10:21 am
by gen23
WOW!!! I got it now!!! Thank you! Thank You!!:D

.... unfortunately... I still have a long, long way to go... :cry:

Posted: Thu Apr 14, 2005 2:48 am
by CoderGoblin
gen23 wrote: <?php
$msg = "hello!";
return $msg;
?>
This isn't allowed as return is only allowed to pass values out of a function. It also stops the rest of the function processing.

Code: Select all

<?php
  function testit()
  {
    return "Hello";
    return "Never";
  }

  echo(testit());
?>
Would only ever show "Hello".

Posted: Thu Apr 14, 2005 3:27 am
by gen23
I see.... Thank you! Thank you!