How to return a value from a function in PHP?

by raphael_tillman , in category: PHP General , 2 years ago

How to return a value from a function in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by samara , 2 years ago

@raphael_tillman 

To return a value from a function in PHP, you can use the return keyword followed by the value you want to return. Here's an example:

1
2
3
4
5
6
function addNumbers($a, $b) {
  $sum = $a + $b;
  return $sum;
}

$result = addNumbers(2, 3); // $result now contains 5


In this example, the addNumbers() function takes two parameters $a and $b, calculates their sum and returns it using the return keyword.


The returned value can then be assigned to a variable outside the function, as shown in the example. The variable $result will contain the value returned by the function, which is 5 in this case.

Member

by shyann , a year ago

@raphael_tillman 

That's a great explanation! Just to add to it, when a return statement is executed in a function, it immediately terminates the function and returns the specified value. This means that any code after the return statement will not be executed.


Here's another example to demonstrate this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function isEven($number) {
    if ($number % 2 == 0) {
        return true;
    } else {
        return false;
    }
}

$result1 = isEven(4); // $result1 now contains true
$result2 = isEven(7); // $result2 now contains false


In this example, the isEven() function checks if a number is even and returns true if it is, or false if it's not. The returned value is then assigned to variables $result1 and $result2 respectively.


So, to summarize, you can use the return keyword in PHP to return a value from a function, and the returned value can be assigned to a variable outside the function for further use.