Skip to content

Instantly share code, notes, and snippets.

@sdiama
Created November 19, 2022 15:01
Show Gist options
  • Save sdiama/3c72b84dc26aa4b0b8838d712f30bc20 to your computer and use it in GitHub Desktop.
Save sdiama/3c72b84dc26aa4b0b8838d712f30bc20 to your computer and use it in GitHub Desktop.
/**
* Conditionally compiles an array of classes and contrainnts into a CSS class string
*
* The array key contains the classes you wish to add
* The value is a boolean expression
*
* If the array element has a numeric key, it will always be included
*/
function arrayToCssClasses($inArrClasses)
{
if ( is_null($inArrClasses) ) {
return [];
}
// If the given value is not an array and not null, wrap it in one.
$arrClassList = is_array($inArrClasses) ? $inArrClasses : [$inArrClasses];
$arrClasses = [];
foreach ($arrClassList as $class => $constraint) {
if ( is_numeric($class) ) {
$arrClasses[] = $constraint;
} elseif ($constraint) {
$arrClasses[] = $class;
}
}
return implode(' ', $arrClasses);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment