How to return a value from a function in PHP?

by raphael_tillman , in category: PHP General , 6 months ago

How to return a value from a function in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 6 months 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.