Skip to content

Instantly share code, notes, and snippets.

@Flushot
Last active February 7, 2017 12:12
Show Gist options
  • Save Flushot/d8f4c9611befb7c9b18d2b4de15b3825 to your computer and use it in GitHub Desktop.
Save Flushot/d8f4c9611befb7c9b18d2b4de15b3825 to your computer and use it in GitHub Desktop.
<?php
function classNames() {
return join(' ',
array_map(
function ($arg) {
if (is_array($arg)) {
$values = [];
foreach ($arg as $className => $show) {
if ($show) {
$values[] = $className;
}
}
return join(' ', $values);
} elseif (is_string($arg)) {
return $arg;
} else {
throw new InvalidArgumentException("argument must be a string or object");
}
},
func_get_args()
)
);
}
?>
<!-- Test case -->
<?
$show_spangle = true;
$show_blah = false;
?>
<!-- Old way -->
<div class="foo bar <?php if ($show_spangle): ?>spangle<? endif ?> <?php if ($show_blah): ?>blah<?php endif ?>"></div>
<!-- New way -->
<div class="<?= classNames('foo', 'bar', ['spangle' => $show_spangle, 'blah' => $show_blah]) ?>"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment