An open API service indexing awesome lists of open source software.

https://github.com/lemmon/clsx-php


https://github.com/lemmon/clsx-php

Last synced: 11 months ago
JSON representation

Awesome Lists containing this project

README

          

# clsx.php

> A tiny PHP utility to conditionally build `class` attribute strings.
> Inspired by [clsx for JavaScript](https://github.com/lukeed/clsx), it lets you easily compose class names using strings, arrays, and associative arrays.

---

## Installation

Install via Composer:

```bash
composer require lemmon/clsx
```

---

## Usage

```php
echo clsx('foo', true && 'bar', 'baz');
// Output: 'foo bar baz'

echo clsx(['foo', 0, false, 'bar']);
// Output: 'foo bar'

echo clsx(['foo'], ['', 0, false, 'bar'], [['baz', [['hello'], 'there']]], 'bye');
// Output: 'foo bar baz hello there bye'

echo clsx(['foo' => true, 'bar' => false, 'baz' => isSomethingTrue()]);
// Output: 'foo baz'

echo clsx(['foo' => true], ['--special' => 'active']);
// Output: 'foo --special'
```

---

## API

### `clsx(...$args): string`

Returns a space-separated string of valid class names.

#### Parameters

- `...$args`: mixed
Accepts any number of arguments. Arguments can be:
- Strings
- Arrays (flat or nested)
- Associative arrays (keys are class names, values are booleans or strings)

> **Note:** Falsy values like `false`, `null`, `0`, `''`, etc. are discarded.
> Only truthy values or valid strings are included in the final result.

#### Example

```php
clsx(true, false, '', null, 0);
// Output: ''
```

---

## License

MIT © [Jakub Pelák](https://www.jakubpelak.com/)