Menü schliessen
Created: April 30th 2025
Last updated: April 30th 2025
Categories: Common Web Development,  Php,  Wordpress
Author: Miljan Puzovic

Conditional CSS classes in PHP project

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

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
    ]); ?>"
>