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.

Example

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

// If we're on the blog page (is_home() is a WordPress function)
if(is_home()) {
    $css_classes[] = 'btn--large';
    $css_classes[] = 'btn--wide';
}

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

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

References

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.