conditionals in a variable?

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
decoy1
Forum Commoner
Posts: 50
Joined: Fri Feb 21, 2003 1:33 pm
Location: St. Louis

conditionals in a variable?

Post 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
bjg
Forum Newbie
Posts: 15
Joined: Tue Jun 10, 2003 9:42 am
Location: .au

Post 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.
Post Reply