How can arrays be effectively used to return multiple values from a PHP function?
When a PHP function needs to return multiple values, using an array is an effective solution. By storing the values in an array and returning the array from the function, you can easily access all the values in the calling code. This approach allows you to return an arbitrary number of values without the need to define multiple return types or use complex data structures.
function getMultipleValues() {
$value1 = 'First value';
$value2 = 'Second value';
$value3 = 'Third value';
return [$value1, $value2, $value3];
}
// Call the function and store the returned values in an array
$result = getMultipleValues();
// Access the individual values from the returned array
echo $result[0]; // Output: First value
echo $result[1]; // Output: Second value
echo $result[2]; // Output: Third value