Don't mix decisions (if ...
) with output. Prepare everything before echoing:
foreach ($dag as $taak) {
// Don't add color by default
$style = '';
// Special color for special entries
if ($_SESSION['user_id'] == $taak['username']) {
$style = ' style="color: red;"';
}
// Make sure HTML special characters in $taak['username'] do not break the HTML
$username = htmlspecialchars($taak['username']);
// Display
echo("<li{$style}>{$taak['taak_naam']} - {$username}</li>");
}
By surrounding the string in double quotes ("
), PHP recognizes variable names inside it and replaces them with their values.
The curly braces ({
and }
) around the array values tell PHP the variable is $taak['taak_naam']
, otherwise it finds only $taak
and it outputs Array['taak_naam']
(which is not what we want).
If a value you use to create HTML content might contain characters that are special in HTML then you must encode those characters using their correct HTML definition. The PHP function htmlspecialchars()
knows how to do it.
It encodes <
, >
, &
and "
(these are HTML breakers if they are not encoded properly). If you need to encode all the symbols that are defined in HTML as "character entities" you can use the PHP function htmlentities()
instead.