Create String from Array with implode()

By using the PHP implode() function you can easily add items to an array and then output them as a single string.

// Create initial array of CSS classes
$css_classes = array('btn');

// Add some classes (could be inside a conditional)
$css_classes[] = 'btn--large';
$css_classes[] = 'btn--wide';

// Convert array to string
$css_classes = implode(' ', $css_classes);
// Example
<a class="<?php echo $css_classes; ?>" href="#">Button!</a>

// Output
<a class="btn btn--large btn--wide" href="#">Button!</a>


Inspirational Newsletter

Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.

No spam. You can unsubscribe at any time.