Mac Luc
Mac Luc

Reputation: 1001

PHP how to return variable without echo

Im looking to return one or another string variable from my php function.
I dont want to echo the string in the function i just want to return the variable, and then output it later in the code.
The following code represents my code (simplified):

<?php
$a = NULL;
$b = NULL;
myFunction($this);
function myFunction($this) {
   if($this === a) {
       return $a = "its a";
   }else{
       return $another = "its something else";
   }
}
?>
<html>
   MARKUP
   <?php echo $a; ?>
   <?php echo $b; ?>

Upvotes: 1

Views: 3612

Answers (3)

Arnaud
Arnaud

Reputation: 80

I think you misunderstand how to work functions.

function myFunction($this, $a) {
   if($this === $a) {
       return "its a";
   }else{
       return "its something else";
   }
}
$result = myFunction($this, $a);

I think you want to do this

Upvotes: 5

Samuel Allan
Samuel Allan

Reputation: 392

As an addition to all the other answers I think your problem might be that you never define $thisand also how are you planning to echo the value of myFunction(...) later if you never store it anywhere? If I understand what you are trying to do correctly this code should work:

<?php
$a = NULL;
$b = NULL;
$another = NULL;
$aaa = myFunction($this);
function myFunction($that)
{
  $result = -1;
  if($that === $a)
  {
    $a = "it's the good 'n old a";
    $result = 0;
  }
  else
  {
    $another = "Hey it's someone else";
    $result = 1;
  }
  return result;
}
?>
<div id="div a">
<?php
if($aaa == 0)
{
  echo $a;
}
?> 
</div>
<div id="div b">
<?php
if($aaa == 1)
{
  echo $another;
}
?>
</div>

Upvotes: 0

Kaleem Sajid
Kaleem Sajid

Reputation: 230

$store_var_value = myFunction($this);

You can save returned value in a variable to use it later.

Upvotes: 2

Related Questions