Can anyone help me fix this php string mess?
echo '<nav ><a href="' . $route . '" '.($_SERVER['REQUEST_URI'] == '/' . $route) ? 'style="color:' . $currentPathColor . '"' : '' . '>' . $route . '</a></nav>';
This is whats supposed to do(this works):
if ($_SERVER['REQUEST_URI'] == '/' . $route) {
echo '<nav ><a href="' . $route . '" style="color:' . $currentPathColor . '">' . $route . '</a></nav>';
} else {
echo '<nav ><a href="' . $route . '">' . $route . '</a></nav>';
}
Just practicing PHP for the purpose of knowing something about it, thanks in advance!
CodePudding user response:
As PHP is a template engine, you can make use of it and maintain readability.
$style = ($_SERVER['REQUEST_URI'] === "/$route") ? "style='color:$currentPathColor'" : '';
echo <<<_HTML
<nav ><a href="$route" $style>$route</a></nav>
_HTML;
CodePudding user response:
I can understand wanting to reduce repetition of code, and as such I would suggest putting the common html in two separate parts with an if
in the middle. This achieves the same as you are trying to get but with (IMHO) a more maintainable structure...
echo '<nav ><a href="' . $route;
if ($_SERVER['REQUEST_URI'] == '/' . $route) {
echo '" style="color:' . $currentPathColor;
}
echo '">' . $route . '</a></nav>';
( I have not tested this, so can't 100% guarantee the quotes are correct, but I hope you get the idea.)
CodePudding user response:
Others have given some reasonable alternative styles, but to address the immediate problem, your issue is one of operator precedence.
In order of precedence, you have:
- A parenthesised expression
- The
.
concatenation operator - The ternary
?:
operator
So PHP evaluates things a bit like this:
// Parentheses
$boolean = $_SERVER['REQUEST_URI'] == '/' . $route;
// Concatenation
$string_1 = '<nav ><a href="' . $route . '" '. $boolean;
$string_2 = 'style="color:' . $currentPathColor . '"';
$string_3 = '' . '>' . $route . '</a></nav>';
// Ternary
$chosen_string = $string_1 ? $string_2 : $string_3;
// echo
echo $chosen_string;
But what you wanted was this:
// String sections
$prefix = '<nav ><a href="' . $route . '" ';
$suffix_a = 'style="color:' . $currentPathColor . '"';
$suffix_b = '' . '>' . $route . '</a></nav>';
// Condition
$condition = $_SERVER['REQUEST_URI'] == '/' . $route;
// Ternary
$chosen_suffix = $condition ? $suffix_a : $suffix_b;
// Combine
$string = $prefix . $chosen_suffix;
// echo
echo $string;
So as well as parentheses around the condition, you want parentheses around the whole "suffix" section, so that that gets evaluated first:
echo
'<nav ><a href="' . $route . '" '
.
(
( $_SERVER['REQUEST_URI'] == '/' . $route )
?
'style="color:' . $currentPathColor . '"'
:
'' . '>' . $route . '</a></nav>'
);
Since this kind of mistake is so easy to make, and the result easy to misinterpret, it's generally a good idea to simply avoid complex expressions like this, and introduce intermediate variables, use if
statements, and so on.