Echo from function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Pazuzu156
Forum Contributor
Posts: 241
Joined: Sat Nov 20, 2010 9:00 pm
Location: GA, USA
Contact:

Echo from function

Post 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. :)
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
Dorin85
Forum Newbie
Posts: 20
Joined: Tue Aug 16, 2011 3:16 pm

Re: Echo from function

Post 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>
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: Echo from function

Post 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>
User avatar
Pazuzu156
Forum Contributor
Posts: 241
Joined: Sat Nov 20, 2010 9:00 pm
Location: GA, USA
Contact:

Re: Echo from function

Post 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.
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
Post Reply