← Back to Chapters

PHP Function with Returning Value

? PHP Function with Returning Value

? Quick Overview

In PHP, functions can return values, which allows you to store the result in variables or use it directly in expressions. Advanced cases involve returning arrays, objects, or using conditional returns.

? Key Concepts

  • Functions can return data using the return keyword
  • Returned values can be stored, echoed, or reused
  • Multiple data can be returned using arrays or objects

? Syntax / Theory

? View Code Example
// Basic function syntax with return value
function functionName($param1, $param2) {
return $param1 + $param2;
}
$result = functionName(5,10);

? Example 1: Returning a Simple Value

? View Code Example
// Function returning a single numeric value
<?php
function add($a,$b){
return $a + $b;
}
echo add(5,10);
?>

? Example 2: Returning an Array

? View Code Example
// Function returning multiple values as an array
<?php
function getUserInfo(){
return ['name'=>'Alice','email'=>'alice@example.com'];
}
$user = getUserInfo();
echo $user['name'];
echo $user['email'];
?>

? Example 3: Conditional Return

? View Code Example
// Function returning different values based on condition
<?php
function checkAge($age){
if($age >= 18){
return "Adult";
}
return "Minor";
}
echo checkAge(20);
?>

? Example 4: Returning Objects

? View Code Example
// Function returning an object instance
<?php
class Person{
public $name;
function __construct($name){
$this->name = $name;
}
}
function createPerson($name){
return new Person($name);
}
$p = createPerson("Bob");
echo $p->name;
?>

? Live Output / Explanation

The returned value replaces the function call. PHP immediately exits the function once return is executed.

? Interactive Example

Conceptual flow of function return:

Function Return Value

? Use Cases

  • Calculations and data processing
  • Fetching database results
  • Generating reusable logic blocks

✅ Tips & Best Practices

  • Always return consistent data types
  • Use type hints in modern PHP
  • Keep functions single-purpose

? Try It Yourself

  • Create a function that returns the maximum value of an array
  • Return associative user data and print email
  • Return different objects based on parameters