Page 1 of 1

Echo from function

Posted: Thu Aug 18, 2011 2:25 pm
by Pazuzu156
The name doesn't explain well, but what I'm tying to achieve is probably a smack in the face when i get the answer. What I want is to be able to return a string from a function to be echoed out somewhere else on the page.

Example:

Code: Select all

<?php
function myFunction($get) {
  $get = $_GET['val'];
  if($get!='defined_value') {
    $msg = 'You are using the wrong value!';
  } else {
    $msg = 'You are using the correct value!';
  }
}
return $msg;
?>

Code: Select all

<div id="response"> <?php echo "This is where I want my function's value returned."; ?> </div>
Does anyone think they can help me at all with this? Thanks to any who take this simple task on. :)

Re: Echo from function

Posted: Thu Aug 18, 2011 2:39 pm
by Dorin85
Move the return into the function. Also you don't need to pass "$get" as a parameter if you're immediately overwriting it.

Code: Select all

<?php
function myFunction() {
  $get = $_GET['val'];
  if($get!='defined_value') {
    $msg = 'You are using the wrong value!';
  } else {
    $msg = 'You are using the correct value!';
  }
return $msg;
}
?>
"Include" your php file and replace your text with the function call.

Code: Select all

<div id="response"> <?php print(myFunction()); ?> </div>

Re: Echo from function

Posted: Thu Aug 18, 2011 2:57 pm
by oscardog
Although there really is no need for parentheses on the print call, the following would work the same and, considering how many times you use print/echo, will save lots of time in the long run.

Code: Select all

<div id="response"> <?php print myFunction(); ?> </div>

Re: Echo from function

Posted: Thu Aug 18, 2011 9:56 pm
by Pazuzu156
Dorin85 wrote:Move the return into the function.
I meant to put the return in the function, my bad. :p

And thanks, I told you the answer would be a smack in the face lol. But anyone else who reads this it may help them.