Page 1 of 1

conditionals in a variable?

Posted: Tue Jun 17, 2003 12:44 am
by decoy1
Hi,

I am wanting to know if it is possible to put if/else conditionals in a variable?

Here is some example code

Code: Select all

$table = 
'<table width=75% cellpadding=2 cellspacing=1 border=0>
<tr>
<td valign=top>' 
.$mydomain = 'http://localhost/';
if(!eregi("$mydomain", $_SERVER&#1111;'HTTP_REFERER']))
&#123;
  echo '<img src=""images/image1.gif>';
&#125;
else
&#123;
  echo '<img src=""../images/image1.gif>';
&#125;.
'</td></tr></table>';
Thanks for any input

Posted: Tue Jun 17, 2003 1:56 am
by bjg
You can't include code within variable declarations. Not only that, but you wouldn't want to. Would make your code quite messy and not very well maintainable.

The proper way to do it is using the ternary operator:

http://au2.php.net/manual/en/language.o ... arison.php

You may want to read about strings and concatenation too..

For your example, it'd be best off written like:

Code: Select all

$mydomain = "http://localhost/";
$table = "<table width=75% cellpadding=2 cellspacing=1 border=0><tr><td valign=top>"
."<img src=".(eregi($mydomain, $_SERVER&#1111;"HTTP_REFERER"]) ? "../" : "")."images/image1.gif"
."</td></tr></table>";
I should also note that eregi() isn't a good function to use if you're not using regexps. If you just want to find out if a string occurs in a string, the manual says strpos() is the fastest and less memory intensive way. So i'd change it with strpos($_SERVER['HTTP_REFERER'], $mydomain) instead.