Learn how to convert an array to a CSS, LESS or SASS rule in a string format.

How to convert a nested PHP array to a CSS, SASS, LESS rule (string)

A lot of aspects of an application can be automatized, for example the generation of stylesheets. As a backend developer, you wouldn't mess up with stylesheets directly with files, but instead, generating them with some PHP code, for example using arrays, is the best option.

In this article, we'll show you how to generate a CSS string from an associative array easily.

1. Function to convert an associative array to a css string

To convert an array to a CSS string (with rules or simple variables in the case of SASS or LESS) in PHP, we will use the following function:

<?php
/**
 * Recursive function that generates from a a multidimensional array of CSS rules, a valid CSS string.
 *
 * @param array $rules
 *   An array of CSS rules in the form of:
 *   array('selector'=>array('property' => 'value')). Also supports selector
 *   nesting, e.g.,
 *   array('selector' => array('selector'=>array('property' => 'value'))).
 *
 * @return string A CSS string of rules. This is not wrapped in <style> tags.
 * @source http://matthewgrasmick.com/article/convert-nested-php-array-css-string
 */
function css_array_to_css($rules, $indent = 0) {
    $css = '';
    $prefix = str_repeat('  ', $indent);

    foreach ($rules as $key => $value) {
        if (is_array($value)) {
            $selector = $key;
            $properties = $value;

            $css .= $prefix . "$selector {\n";
            $css .= $prefix . css_array_to_css($properties, $indent + 1);
            $css .= $prefix . "}\n";
        } else {
            $property = $key;
            $css .= $prefix . "$property: $value;\n";
        }
    }

    return $css;
}

The function, basically expects as first argument an array that contains either rules or simple properties of CSS, where every key => value that isn't an array will be expressed as key : value;, if the value of the key is an array, a rule of css will be introduced, assuming that it contains more css properties and so on as the function is recursive.

This function doesn't belong to Our Code World but to the original article of Grasmash (Matthew Grasmick).

2. Usage

As mentioned in the explanation of the function, it returns a CSS string from an array with the specified rules. The function works correctly for plain CSS rules, media queries, SASS and LESS as long as the structure of the array is valid. For example:

CSS

To generate basic CSS rules, simply declare an array where every key is a class selector and its value is an array with the rules:

<?php 

$stylesheet = array(
    "body" => array(
        "margin" => "0",
        "font-size" => "1rem",
        "font-weight" => 400,
        "line-height" => 1.5,
        "color" => "#212529",
        "text-align" => "left",
        "background-color" => "#fff"
    ),
    ".form-control" => array(
        "display" => "block",
        "width" => "100%!important",
        "font-size" => "1em",
        "background-color" => "#fff",
        "border-radius" => ".25rem"
    )
);

echo css_array_to_css($stylesheet);

The previous snippet would output the following CSS rules:

body {
  margin: 0;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #212529;
  text-align: left;
  background-color: #fff;
}
.form-control {
  display: block;
  width: 100%!important;
  font-size: 1em;
  background-color: #fff;
  border-radius: .25rem;
}

SASS/SCSS

Thanks to the recursive implementation, you will be able to nest multiple rules inside a rule, which allows you to generate valid syntax for SASS as well:

<?php 

$sass = array(
    "nav" => array(
        "ul" => array(
            "margin" => 0,
            "padding" => 0,
            "list-style" => "none"
        ),
        "li" => array(
            "display" => "inline-block"
        ),
        "a" => array(
            "display" => "block",
            "padding" => "6px 12px",
            "text-decoration" => "none"
        )
    )
);

echo css_array_to_css($sass);

The previous snippet would output the following SASS code:

nav {
  ul {
      margin: 0;
      padding: 0;
      list-style: none;
  }
  li {
      display: inline-block;
  }
  a {
      display: block;
      padding: 6px 12px;
      text-decoration: none;
  }
}

LESS

In the same way that SASS works, you will be able to write even complex rules as well with LESS:

<?php 

$less = array(
    "@nice-blue" => "#5B83AD",
    "@light-blue" => "@nice-blue + #111",
    "#header" => array(
        "color" => "@light-blue"
    ),

    ".component" => array(
        "width" => "300px",
        "@media (min-width: 768px)" => array(
            "width" => "600px",
            "@media (min-resolution: 192dpi)" => array(
                "background-image" => "url(/img/retina2x.png)"
            )
        ),
        "@media (min-width: 1280px)" => array(
            "width" => "800px"
        )
    )
);

echo css_array_to_css($less);

The previous snippet would output the following LESS code:

@nice-blue: #5B83AD;
@light-blue: @nice-blue + #111;
#header {
  color: @light-blue;
}
.component {
  width: 300px;
  @media (min-width: 768px) {
    width: 600px;
    @media (min-resolution: 192dpi) {
          background-image: url(/img/retina2x.png);
    }
  }
  @media (min-width: 1280px) {
      width: 800px;
  }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors