In PHP, what are some alternative approaches to handling scenarios where the input to a function may be an array or a single string?
When dealing with scenarios where the input to a function may be an array or a single string, one approach is to check the type of the input using the `is_array()` function and then handle the input accordingly. Another approach is to always convert the input into an array, even if it's a single string, to ensure consistency in how the input is processed within the function.
function processInput($input) {
if (is_array($input)) {
foreach ($input as $value) {
// Process each element of the array
echo $value . "<br>";
}
} else {
// Convert single string input into an array
$input = [$input];
foreach ($input as $value) {
// Process the single string input
echo $value . "<br>";
}
}
}
// Test the function with an array input
$inputArray = ["apple", "banana", "cherry"];
processInput($inputArray);
// Test the function with a single string input
$inputString = "orange";
processInput($inputString);