Could we help you? Please click the banners. We are young and desperately need the money
If you're working in a PHP project where you need to print multiple CSS classes on some element your code could quite quickly became a mess. Especially if in the beginning it was only one conditional class but later there was more and there is no time to refactor the code.
The code could become something like this:
<button class="<?php echo $active === true ? 'btn-active' : ''; ?><?php echo $disabled === true ? 'btn-disabled' : ''; ?><?php echo $error === true ? 'btn-error' : ''; ?>">
which would do the job but the code would be quite long, repetitive and unreadable.
Instead, we could do something inspired by @class() directive in Laravel.
First, let's create a helper function getClasses():
function classNames(array $classes) {
$result = [];
foreach ($classes as $class => $condition) {
// If the key is numeric, it's a class that should always be included
if (is_numeric($class)) {
$result[] = $condition;
}
// Otherwise, include the class only if the condition is true
else if ($condition) {
$result[] = $class;
}
}
return implode(' ', $result);
}
and then we can use it like this:
<button class="<?php echo classNames([ 'btn', // Always included 'btn-primary', // Always included 'btn-active' => $isActive, // Included when $isActive is true 'btn-error' => $hasError, // Included when $hasError is true "btn-{$size}" => !empty($size) // Dynamically includes btn-large ]); ?>" >