Created
June 13, 2023 12:22
-
-
Save Sairahcaz/c66b853dcb7c7cb940cc1ec8f9348009 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simply call it like: