You are viewing...

Ugly Syntax in PHP – Executing Conditional Statements in a String

Updated on January 06, 2011 at the 22th hour
Posted under:

DISCLAIMER: Expressed views on this blog are my own.

I’ve been hanging out on Stack Overflow helping people recently, which is great because now I see some value in helping others as I see how other people tend to fall into problems and how other people’s answers differ from the way I would code or answer. There are its pros and cons. This is just one of the cons… read on.

So this guy asks “is there a way to execute a variable conditional statement within a string.” I looked at what he wanted which was:
<?php echo "Hello {isset($name) ? $name : 'World'}!n"; ?>

I answered with a standard answer
$string = isset($name) ? $name : 'World';$result = "Hello $string!n";echo $result;

Which works, but it is not what he wants. Why does he want to do this anyway? It looks as pointless as trying to hack CSS to conform to different browsers all within CSS. He claims it for readability issues. READABILITY MY ASS, my code is as readable as it gets (maybe I’m exaggerating). Apparently, someone finally answers with what he exactly wanted to do:
$default = "World";$name = "Dunes";echo "Hello {${isset($name) ? 'name' : 'default'}}";

What the hell? Why would anyone want to do this? It is a mess. How is this “more readable” in any way? In what way could executing a conditional statement within a string be readable? I guess if there were a super magical way to do
echo “<div style=’border: {1px solid black | 1px dotted green, ($var)}’></div>”;

using PHP where $var is some index pointing to which one to use then I’d applaud the developers because that is somewhat more readable than the above answer.

I highly suggest that you as a reader/programmer never engage in writing code that executes conditions within a string. If you need to put something in a string use str_replace() and put a token (such as [SELECTED]) in the string, so you can replace it with whatever you want. Heck, you can get as crazy and geeky as any old programmer and use RegEx or PRegEx functions in PHP to search and replace.

Here’s the link to the Stack Overflow Question: In PHP, is conditional variable substitution possible?

Kudos to Jeff Atwood and the rest of the guys who created Stack Overflow!
You just read "Ugly Syntax in PHP – Executing Conditional Statements in a String". Please share if you liked it!
You can read more recent posts here.