Search code examples
phpif-statementechois-empty

How to equate an echo value to a variable and access that variable somewhere else


I want to echo a value, but hold it as a variable to access that value later.

  1. What's the right syntax for the following?

    if (!empty($row['A'])){
        $Test = echo '<span>sale</span>';
    }
    
  2. How do i prevent the above PHP block from printing and only print when that variable when is called somewhere like as in.

    echo $test;
    
  3. Is there a way to put function inside echo?

like.

echo 'echo this is a 'if (!empty($row['A'])){
    $Test = echo '<span">function</span>';
}''.

I know the above is wrong, please give a reason for your downvote if you are gonna downvote. Thanks.


Solution

  • You don't need to store echo in the variable. When you want to use the variable later, that is when you call echo. Your code should look like:

    $test = (!empty($row['A'])) ? 'sale' : '';
    

    This is a ternary operator which is basically a shorthand for the following if/else:

    if(!empty($row['A'])) {
        $test = 'sale';
    } else {
        $test = '';
    }
    

    In this case, I set it to an empty string if $row[a] is empty so nothing bad happens if you echo it later. (You want to make sure your variable is defined no matter what, so you don't cause an error by trying to call an undefined variable.)

    Then, to use it, simply call

    echo $test;
    

    Why do you want to put the function inside of an echo? That defeats the point of storing a variable in the first place.