Skip to content

Instantly share code, notes, and snippets.

@Sairahcaz
Created June 13, 2023 12:22
Show Gist options
  • Save Sairahcaz/c66b853dcb7c7cb940cc1ec8f9348009 to your computer and use it in GitHub Desktop.
Save Sairahcaz/c66b853dcb7c7cb940cc1ec8f9348009 to your computer and use it in GitHub Desktop.
<?php
/**
* A php 8 like match expression for php 7
*
* @param $value
* @param array $expressionArray
* @return mixed
* @throws Exception
*/
function matchExpression($value, array $expressionArray) {
// Check if value exists in the keys of the expression array
if (array_key_exists($value, $expressionArray)) {
// If the corresponding value is a closure, execute it
if (is_callable($expressionArray[$value])) {
return $expressionArray[$value]();
} else {
// Otherwise, return the corresponding value
return $expressionArray[$value];
}
} elseif (array_key_exists('default', $expressionArray)) {
// If 'default' key exists, check if its value is a closure
if (is_callable($expressionArray['default'])) {
return $expressionArray['default']();
} else {
// Otherwise, return its value
return $expressionArray['default'];
}
} else {
// If the key doesn't exist and no 'default' is provided, throw an exception
throw new Exception("Match expression not found for the provided value");
}
}
@Sairahcaz
Copy link
Author

Sairahcaz commented Jun 13, 2023

Simply call it like:

$food = 'cake';

$match = matchExpression($food, [
    'apple' => 'This food is an apple',
    'bar' => 'This food is a bar',
    'cake' => function() { return 'This food is a cake'; },
    'default' => function() { return 'This is an unknown food'; },
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment