Function return, i am confused

hi folks,
i have trouble getting my head around why would we use return in function and later call it. i can’t make sense of it. can anyone explain
p.s - i did my research but nothing i can comprehend

Why you would call return twice in a function? You might want to leave the function at different points.

Which is easier to read?

$a = 4*4*4*4*4*4;
$b = 3*3*3*3*3*3*3;
$c = 2*2*2;
$d = 9*9*9*9*9*9*9*9*9*9*9;


$a = pow(4, 6);
$b = pow(3, 7);
$c = pow(2, 3);
$d = pow(9, 11);

At their heart functions allow code that would otherwise need to be typed in repeatedly to be put in one place.

The most classic example of having more than one return is a recursive function. Lets try… Factorializing a number.

function recurse($in) {
  if ($in == 1) {
    return $in; //We've hit our special 'stop' condition. Return 1.
  return $in * recurse($in-1); //We've got a ways to go yet. build the chain.

echo recurse(5); //120

Don’t muddy the waters with recursion please. Read what he’s writing carefully - he’s having trouble grasping the reason why we write functions at all. I doubt OP is ready to even attempt to grasp what a recursive function is and how it’s used.

That is, when someone asks a CS 101 question, don’t respond with a 300 level answer.

I don’t have problem grasping functions at all. i can’t grasp why do we return return in a function and later call that function. the return function confuses me

The return statement passes a value back to whatever called the function. That value is usually the result of the operation of the function. I’m sorry, but I don’t think I can make it any clearer than I already have.

First better make sure he’s asking a CS 101 question - as it seems neither you nor I got it right.

Perhaps this might help? We first need to define the function otherwise php won’t know what to do. As an example,

<?php function add($a,$b) {
return $a+$b;}

echo $sum;?>

First I define my function. The function with the name “add” will take whatever 2 numbers I give it, add them together and then give me back the result (that’s the “return”). Now that I’ve defined it, I can call it. Setting $sum =add(3,4) will define $sum as the result of adding 3 and 4 together. I then print it out (but you don’t have to!) using echo.

Note that since I’ve defined it first, I can call it anywhere else lower in my script.

Hope this helps…

Off Topic:

@starlion you may want to put a check in that function of yours to disallow for negative numbers :smiley: