Home > Article > Backend Development > How do PHP functions return mixed data types?
PHP functions can return mixed data types, including integers, strings, booleans, or arrays, simply by passing multiple types of values as return values. Practical examples include calculating the total price of the shopping cart and returning an array of total price and discount. NOTE: Document return value types, use type checking to ensure the correct return type, use mixed data types with caution, and consider using the Union type to specify the types that a function can return.
How PHP functions return mixed data types
In PHP, functions can return any data type, including mixed data types. Mixed data types are when a function can return multiple types of data, such as integers, strings, booleans, or arrays.
To return mixed data types, just use multiple types of values as the return value of the function. For example:
function get_data() { return array('name' => 'John Doe', 'age' => 30); }
This function returns an array containing name and age.
Practical Case
Consider a function that calculates the total price of the user's shopping cart:
function calculate_total($items) { $total = 0; foreach ($items as $item) { $total += $item['price']; } return array('total' => $total, 'discount' => 0.1); }
This function returns an array containing the total price of the shopping cart and A 10% discount.
Notes
The above is the detailed content of How do PHP functions return mixed data types?. For more information, please follow other related articles on the PHP Chinese website!