-3

Possible Duplicate:
How to clear previously echoed items in PHP

I have this code:

<?php

$var = true;
echo 'testing';

if ($var)
{
    echo 'Hey'; //The only thing that should appear.
}
?>

How would I do to only make "Hey" appear on the site?

Community
  • 1
  • 1
Chengy
  • 619
  • 1
  • 7
  • 17
  • 3
    By removing the line `echo 'testing'`. – GolezTrol Jan 02 '13 at 21:14
  • I don't think what you want to do is possible. As far as I know (and I could certainly be wrong), `echo` sends data back to the requester immediately. Alos, why are you echoing something if you don't want it shown to the client? – brettkelly Jan 02 '13 at 21:15
  • @inkedmn Data is not pushed to the browser until the response is sent. Clever use of buffers and/or managing `STDOUT` can be used to override output via `echo` or similar functions. – phpisuber01 Jan 02 '13 at 21:17
  • Over complicating it just do make a word appear on his page.. – Sir Jan 02 '13 at 21:27

3 Answers3

10

Without being too complicated... You can just assign your output to a variable and overwrite it.

$var = true;
$output = 'testing';

if($var)
{
    $output = 'Hey';
}

echo $output;

Alternatively, (the more complex route), you can use buffers. Research ob_start to get started learning about that.

phpisuber01
  • 7,585
  • 3
  • 22
  • 26
5

You could use output buffering:

<?php
ob_start();
$var = true;
echo "testing";
if($var) {
    ob_clean();
    echo "Hey";
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 2
    Why is it wrong? It may be an oversimplified example, but I use `ob_clean` occasionally to "delete" output and replace it with an error message. – Niet the Dark Absol Jan 02 '13 at 21:17
  • 2
    @MattiVirkkunen Hard to tell if it's wrong if you don't know the use case. The code in the question is obviously a test. Don't punish people for answering questions. Downvote or close-vote the question instead, or give an answer that *you* think is right. – GolezTrol Jan 02 '13 at 21:17
  • 2
    It's not our job to determine if it's right or wrong. Unless it's a severe security problem like `eval` or SQL injections, it's just not our business. – Niet the Dark Absol Jan 02 '13 at 21:18
  • Something like this I was wanted. Thanks. And yes the code is simplified. It is an error message that will be shown. – Chengy Jan 02 '13 at 21:23
  • Nothing wrong with this answer. Gave the OP exactly what he wanted – Ascherer Jan 02 '13 at 21:34
4

You can't, as it has been printed already.

Here is an alternative solution

<?php
   $var = true;
   if($var)
       echo "Hey";
   else
       echo "testing"
?>
Allan Spreys
  • 5,287
  • 5
  • 39
  • 44