gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
Php how to force function argument to be one of few strings?
- User
Php how to force function argument to be one of few strings?
- Assistant
You can use an enumeration of possible values as the argument type in the function signature. This can be achieved using the
stringtype hint and the|(pipe) character to separate the allowed values:function myFunction(string $arg) { if ($arg !== 'value1' && $arg !== 'value2' && $arg !== 'value3') { throw new InvalidArgumentException('Invalid argument value.'); } // Rest of the function code }Alternatively, if you are using PHP 8 or later, you can use the
enumtype instead:enum AllowedValues: string { case VALUE1 = 'value1'; case VALUE2 = 'value2'; case VALUE3 = 'value3'; } function myFunction(AllowedValues $arg) { // Function code }This approach provides type safety and prevents passing invalid values.