php – Set variable to result of if statement [closed]

The way you want to do this…

To answer the original question re: your formatting, you can use an if statement to define a variable, but it’s not particularly readable:

$myVariable = (strlen($myString) > 0) ? '<p>'.$myString.'</p>' : '';
echo $myVariable;

Live demo.

Recommended way to do this…

However, in your case this is entirely unnecessary, you can use the far more understandable form:

Note: PHP echo does not product an error if passed an undefined variable. It will just echo nothing which I assume is what you want it to do.

if (strlen($myString) > 0) {
    $myVariable="<p>".$myString.'</p>';
}
echo $myVariable;

Live demo with $myString set and empty for the neighsayers.

Added note re strlen performance…

You may find that using if(isset($myString)) is more efficient than using if(strlen($myString)>0): isset (0.064 sec) vs strlen (0.144 sec). If it is possible for $myString to be undefined then strlen becomes up to 3x slower still (0.5 sec) whilst isset becomes faster (0.048 sec).

So your final code should be:

if (isset($myString)) {
    $myVariable="<p>".$myString.'</p>';
}
echo $myVariable;

Browse More Popular Posts

Leave a Comment