PHP code example of lukasss93 / smatch
1. Go to this page and download the library: Download lukasss93/smatch library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
lukasss93 / smatch example snippets
$result = smatch('apple')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->get();
// $result = 'delicious'
$result = smatch('apple')
->case('pear', fn () => 'tasty')
->case('apple', fn () => 'delicious')
->case('banana', fn () => 'yellow')
->get();
// $result = 'delicious'
$result = smatch('chair')
->case(['apple', 'pear', 'banana'], 'fruit')
->case(['table', 'chair'], 'furniture')
->get();
// $result = 'furniture'
$result = smatch('strawberry')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->fallback('invalid')
->get();
// $result = 'invalid'
$result = smatch('strawberry')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->fallback(fn () => 'invalid')
->get();
// $result = 'invalid'
try {
$result = smatch('strawberry')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->get();
} catch (UnhandledSmatchException $e){
echo $e->getMessage();
}
// $e->getMessage() = Unhandled smatch value of type string
$result = smatch('car')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->getOr(fn () => 'complex logic');
// $result = 'complex logic'
$age = 23;
$result = smatch(true)
->case($age >= 65, 'senior')
->case($age >= 25, 'adult')
->case($age >= 18, 'young adult')
->fallback('kid')
->get();
// $result = 'young adult'
$text = 'Bienvenue chez nous';
$result = smatch(true)
->case(str_contains($text, 'Welcome') || str_contains($text, 'Hello'), 'en')
->case(str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour'), 'fr')
->get();
// $result = 'fr'