Current Location: Home> Latest Articles> How PHP Functions Return Mixed Data Types: Implementation and Examples

How PHP Functions Return Mixed Data Types: Implementation and Examples

M66 2025-09-17

Understanding PHP Functions Returning Mixed Data Types

In PHP, functions can return any data type, including mixed data types. Mixed data types mean that a function can return multiple types of data, such as integers, strings, booleans, or arrays.

To return mixed data types, simply include different types of values in the function's return statement. For example:

function get_data() {
  return array('name' => 'John Doe', 'age' => 30);
}

This function returns an array containing a name and an age.

Practical Example: Calculating Shopping Cart Total

Consider a function that calculates the total price of items in a 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 that includes the total cart price and a 10% discount.

Important Considerations When Using Mixed Data Types

  • Ensure that the function's documentation specifies the mixed data types it returns.
  • Use type checks to confirm the function returns the expected types.
  • Use mixed data types cautiously to avoid potential code errors.
  • Consider using union types to explicitly specify the function's return types, improving readability and maintainability.