# Functions, slightly confused to how some use them

Ive been going over functions and I still find it quite confusing.

If you are going to use a function you have to return it…am I right…? Or do you only return it if you only want to use it once (inside the function)?

Return true or false has also really stumped me, I just can’t see its point, if you’re going to use it why not just call it…

I understand more of functions now but the concept of “return” is really sticking me. Can anyone explain it in real laymen terms…

The return statement has various uses in functions.

Its main use is when you assign the function call to a variable, for example:

``````\$SquareRootOfThree = sqrt(3)
\$ThisNumber = 42;
\$SquareRootOfThisNumber = sqrt(\$AnyOtherNumber);
``````

The variables \$SquareRootOfThree and \$SquareRootOfThisNumber will now hold the positive square root of the number you’ve given them. That’s because the sqrt function will return the value.

For example:

``````<?php
function getFirstWord(\$Name){ //oversimplified - a real-use function would most likely handle punctuation etc
\$FirstSpace = strpos(\$Name, ' ');
if(\$FirstSpace === false){
return \$Name;
}
return substr(\$Name, 0, \$FirstSpace - 1);
}
\$Word = getFirstWord('Hello World'); // \$Word = 'Hello'

``````

Also note the multiple return statements. This is another feature of the return statement - it will return the value as described before but will stop the function from going any further. In the above example, the first return is only used if a space isn’t in the sentence; if this is true then the function doesn’t continue.

The reason people generally return true or false is to either return a flag value (i.e. function isItTuesday() would most likely return true if it’s a tuesday) or report whether the function was successful - i.e. in strpos(), a boolean value of false is returned if the search string was not found.

Hope that helps,
Jake Arkinstall

Sorry Jake thanks for your help, I understand the first part but I’m still completely confused. Please don’t use all those scary words, I’m a noobie and everytime I see them my balls tighten with fear.
The most difficult thing about php is the amount of words used for the same thing.

I’ve read your code a few times and appreciate you’ve simplified it for me. I can see what it does to a certain extent but I just can’t see the point in using them. From what I can see, if you only want the function to be used once, in the position it’s written in, then use return ture or false. Lol as I’m writing this Im confusing myself so god knows how you feel.

Why not just write a function, in the curly braces write what you want it to do, include some if statements, loops etc, return it with the function name and then use it.

It just seems llike a long way round to get there…(and a bloody confusing one)

There is one part that I think I understand. I have been looking at some code from w.press. They have returned another function (f2) into the return of the current function(f1). Is this to add it to the result of the function (f1)…?

If you only want to use the function once, in your entire application/website, then there’s no use in making it a function. Just write the code.

…return it with the function name and then use it.

What do you mean by this? Can you give an example?

Regarding the first quote what I meant was writing the function in an includes file, (functions.php) then calling it

As for the second part here is a function returned then used outside of itself.

``````function AddThese (\$first, \$second, \$third)

{
//this is what the function actually does, what happens inside it.
\$answer = \$first + \$second + \$third;

}

//this part to do with Add these function
\$first = 5 ;
\$second = 34 ;
\$third = 237 ;
\$math = AddThese(\$first, \$second, \$third) ;
echo "\$first,  \$second, and \$third add up to: " . \$math ;

?>

``````

With this example it shows “addthese” can be used again later in the pages code… that’s the method to my madness.

So why would I use ‘true or false’… surely ‘if’ and ‘else’ statements can take care of what the user does…?

That’s the general idea, yes What’s so confusing about that?

As for the second part here is a function returned then used outside of itself.

``````function AddThese (\$first, \$second, \$third)

{
//this is what the function actually does, what happens inside it.
\$answer = \$first + \$second + \$third;

}

//this part to do with Add these function
\$first = 5 ;
\$second = 34 ;
\$third = 237 ;
\$math = AddThese(\$first, \$second, \$third) ;
echo "\$first,  \$second, and \$third add up to: " . \$math ;

?>

``````

With this example it shows “addthese” can be used again later in the pages code… that’s the method to my madness.

So why would I use ‘true or false’… surely ‘if’ and ‘else’ statements can take care of what the user does…?

In this case, you wouldn’t use true or false. This function returns the result of the addition of three numbers.

In other cases (Jake already gave an example) it returns true or false. Or it returns a result if everything went ok, and false if it didn’t. For example the php function mysql_fetch_assoc: it returns the next row of the result set if there is any, and FALSE if there are no more rows.

In other cases (Jake already gave an example) it returns true or false. Or it returns a result if everything went ok, and false if it didn’t. For example the php function mysql_fetch_assoc: it returns the next row of the result set if there is any, and FALSE if there are no more rows.

Thanks for your help,

But this is what I don’t understand and I believe this is the wind to blow the fog, how can you return true or false in a function if it hasn’t happened yet…? If you could, roughly categorise when they are used I think that might clear things up as it seems they are used in different situations.

Thanks for your time guys

having an earthquake right now,

If what hasn’t happened yet?

Essentially when you invoke (call) a function you are giving an instruction to some code to do something for you.

The message that function returns to whoever used it (called it) is what you design into your function. That message which is passed back is called the return value.

There are times you might want a function to just do something and if it fails, to just shut up - but these are relatively rare things - so for now always return something.

So generally, you want your function to return one of these 3 things:

[B]true /B which usually equates to “that operation worked fine!”
[B]false /B which usually equates to “nope, something went wrong!”
OR
a value (anything) which is usually the result of what you have asked the function to just get on and do.

Your calling code can then inspect this return value to detect if the operation went well or not.

Here is a contrived example, lets imagine you have a website, or series of websites which deal with peoples’ names, and you are constantly adding first name to second name etc.

``````
function makeProperName(\$name, \$family=null){
if( \$family === null ){
// today you decide that you cannot make a name without the family name
return false;
}
else {
return ucwords(\$name) . ' ' . ucwords(\$family) ;
}
}
/*untested by the way*/

``````

So you have that function, and you keep it in an include file somewhere with some other similar functions you call nameFunctions.php

Now, deep squirreled away in your CMS, or website or forum or whatever, you are doing this.

``````
include 'nameFunctions.php' ;

\$name = "joe";
\$family = "bloggs";

echo 'Welcome back ' . makeProperName(\$name, \$family);

``````

OR, more likely you are doing this:

``````
include 'nameFunctions.php' ;

// \$row = connect to database, get this persons row

echo 'Welcome back ' . makeProperName(\$row['name'], \$row['family']);

``````

In the above case you are using makeProperName(\$row[‘name’], \$row[‘family’]) to be equivalent to a variable which contains the string “Joe Bloggs”.

But what if elsewhere, joe did not tell you his family name, and because family name is a mission critical detail which means you cannot go on (so you should have captured it earlier, right? Remember this is a contrived example, bear with me).

So now you can do :

``````
include 'nameFunctions.php' ;
// \$row = connect to database, get this persons row

\$proper_name = makeProperName(\$row['name'], \$row['family']);

if( \$proper_name !== false){
echo 'Welcome back ' . makeProperName(\$row['name'], \$row['family']);
}
else{
echo 'Hey, what is your family name?'
}

``````

In the above case, if the row for joe has the value null in your database makeProperName(\$row[‘name’], \$row[‘family’]) may well contain the value false or else a valid string.

Now your calling code is testing the return value because you are aware things could have gone wrong viz makeProperName() did not get all the information it needed, so you have then intelligently forked your code.

There are also other benefits to using functions which now start clocking up.

You notice that the variable \$family is used inside the function, that means you are also free to now use that variable name again in another function, and you can use that \$family variable in your calling code without worry of them getting mixed up and overwriting each other.

Now you might argue that you would be just as well doing :

``````
echo 'Welcome back ' . ucwords( \$row['name']) . ' ' . \$ucwords(\$row['family']);

``````

But consider this. Lets say that after a few weeks and having used your famous makeProperName() function in 10 different places you suddenly notice that some people start adding a middle name, and you want to incorporate that into your old makeProperName() function from now on but you don’t want to have to hunt and find those 10 old places.

So you can change the function signature to:

``````
function makeProperName(\$name, \$family=null, \$middle=null){

// insert the middle name where it should go, as long as \$family isset

}

``````

and make the necessary addition to your function - so that it will still return false on failure.

And then oh, you get requests for a French version of your site and there they quite bizarrely write “BLOGGS Joe”… so you have the opportunity to tell makeProperName() do that for you - or this is getting too contrived now?

So functions provide a really cool way to package up discrete but repeated instructions and isolate the code that performs the message - and if you write them correctly you can inspect the return value (message) in order to decide what to do next.

The hardest trick when starting out is to identify likely function candidates which apply to your particular domain, market, niche call it what you will - because it seems all the really obvious ones are already written into php as php functions.

This is my best advice, and there are reasons to break just about all the points I made, but understand why - and keep your functions very very focussed - doing one simple thing and doing it properly.

As for how best to write them, there are always people here who will help you if you ask.

HTH

You also don’t have to return anything in a function (which technically causes it to return null).

Cups has a good explanation, but it may help to understand the “stack”.

A function is essentially a portion of code that can be called any number of times. That’s the simple explanation. However, it is important to have a function do only one thing (one function).

A function may return a value, or it may not. If it returns a value, the value is passed back to wherever it was before. When you call a function, it goes into a set of memory called the “stack”. The stack is basically a stack of function calls. The stack is LIFO (last-in first-out) or FILO (first-in last-out), meaning the last thing added is the first taken off, and vice versa (though the end result is the same). Think of a stack of books. You can only take off the top book (without cheating =p).

So, let’s take this code for example:

``````
function A() {
var a = B();
return a;
}

function B() {
return 5 + C();
}

function C() {
return 3;
}

echo A();

``````

So, if we go through this code step by step:

• Each of the functions do NOTHING when they are passed over.
• The first line of code that does something is the last line, “echo A();”.
• When we reach the “echo A();” line, the A() function is called. A() is also pushed on to the stack. Our stack now has something like:
``````
A() Line 1
Line 14

``````
• We are now processing A(), so we are doing the line “var a = B();”. This line causes B() to be called. When we call B(), it is added to our stack, which looks like this:
``````
B() Line 6
A() Line 2
Line 14

``````
• We are now in B(), doing the line “return 5 + C();”. This then calls C(), which gets added to the stack as well:
``````
C() Line 10
B() Line 7
A() Line 2
Line 14

``````
• Now, C() does the line “return 3;”. The return tells the function it’s basically done. The value afterwards lets it know it needs to send that back to the next thing on the stack. Now that C() is complete, it’s removed from the stack, and 3 is basically put in the place of C().
``````
B() Line 7 -- Given 3
A() Line 2
Line 14

``````
• Now B() takes that 3, adds it to 5 and then returns 8. This value is passed by to A() and B() is removed from the stack.
``````
A() Line 2 -- Given 8
Line 14

``````
• A() takes that 8 and gives it to it’s variable a. It then returns a, which returns 8. A() is removed from the stack.
``````
Line 14 -- Given 8

``````
• 8 is now echo-ed out. Echo is a function as well (just written differently), so echo is added to the stack and is sent 8.
``````
- echo -- Given 8
Line 14

``````
• Echo does it’s thing and returns nothing (null), so it’s removed to the stack.
``````
Line 14

``````
• Line 14 is all done, so we hit the end of our program and we’re done. Line 14 is removed from the stack. Our stack is now empty, so we’re done.

That’s not a 100% technically accurate stack, but it’s the idea that matters at this point. I’ve been doing this for a long time and rarely have to do anything with the stack directly, so it’s not important at this level.

Hope that helps.

Thanks so much for you time guys, thanks for your explanantion of functions and all the code you’ve provided, they are all really helpful.

I’m still a bit unclear, a 7.2 earthquake just shook my building so nerves a bit all over the place, Ill have a good read tommorow and sure it’ll make sense when concentration is better.

Cheers again

I first thought you were speaking about a mental earthquake.
Hope all is well. Where are you living?

Northern Thailand, two of them hit North Eastern Burma which isn’t far from here. The aftershocks are still happening so am kinda on edge at mo, thanks for your concern

Guys thanks for your help and effort, Ive learnt so much to do with functions now that I know it will click soon .

I’ve quoted some parts to try and give you an idea of what Im not getting.

In other cases (Jake already gave an example) it returns true or false. Or it returns a result if everything went ok, and false if it didn’t.

Your calling code can then inspect this return value to detect if the operation went well or not

If I’ve written it already, why would it matter if it went well or not…? I’ve returned “true” or “false”, kinda like I’ve made the decision already.

If it returns a value, the value is passed back to wherever it was before

I understand this slightly I think as in once the return has been done, move onto the next part of code whilst including this result

I get returning a value of some sort but actually writing true or false I am so lost still.

The only concept behind them that I can see and I guess I’m very wrong is to use “true” and ‘false’, kinda like the != and = used in “if” statements, if you can see any relation in this comparison…?

I know this is probably frustrating for you and understand if you’re not sure how you can help anymore, just to reitterate once again that I really appreciate your time and effort I apologise for not getting it yet.

Okay, so, from those two pieces, it kind of looks like you think that the functions are called when it’s gotten to in the code (when the function declaration is reached), i.e., the:

``````
function A() {

``````

line.

However, it’s not called until somewhere else when you do a call like:

``````
var a = A();

``````

This means that whatever your function does, it could wind up with a different result each time it’s ran.

For example, say you have a function which checks to see if some string you pass is a digit.

``````
function isDigit(\$str) {
if(indexOf(\$str, '0123456789)) // simple way to test
return true; // it is a digit
else
return false;
}

``````

That can actually be simplified by just returning the indexOf(), but that’s a lesson for later.

That’s an example of a function returning a value based on what it’s given.

Or consider you were sending an email:

``````
function sendEmail() {
// code to send email here
if(\$emailSent)
return true;
else
return false;
}

``````

In this case you are returning true if the email was sent successfully, or false if there was some kind of error.

That make sense any more?

It’s not frustrating (for me)… this is a problem I’ve explained to countless students of mine. It’s a tricky one to grasp at first and very common. Keep asking questions until you’re sure you have it, this is an extremely vital concept to fully grasp. =)

You write a function to do some task. But once the task is done, you might want to know the result. It all depends on what the function does.
If you need the function to return something, you make it return that something you need. TRUE/FALSE, or any other value (string, number, array, etc).
If you don’t need the function to return something, then don’t return anything. You are writing the function, make it the way you see fit.

A function that might not need to return anything is a function that displays something:

``````
function displayError(\$string) {
echo '<p class="error">' . \$string . '</p>';
}
``````

Now in your script you can call this function any time you need to display an error. You send it the text to display, and it doesn’t return anything.
Example:

``````
<form>
Name: <input type="text" name="name" value="<?php echo \$name; ?>" />
<?php
// if an error for 'name' exists, I call the function to display the error
if (isset(\$error['name']) displayError(\$error['name']);
?>
<?php
// if an error for 'password' exists, I call the function to display the error
?>
</form>

``````

(never mind correct syntax, it’s the idea that’s important ;))

Or you could decide to not do the displaying in the function, but to have it return the text, so you can then do with that text whatever you want (display it, save it in a database, send it to another function, whatever):

``````
function displayError(\$string) {
return '<p class="error">' . \$string . '</p>';
}
``````

Then you can do the echoing (or assigning to a variable) in your code:

``````
<form>
Name: <input type="text" name="name" value="<?php echo \$name; ?>" />
<?php
// if an error for 'name' exists, I call the function and echo the string it returns
if (isset(\$error['name']) echo displayError(\$error['name']);
?>
<?php
// if an error for 'password' exists, I call the function and assign the string it returns to a variable. Then I echo that variable.
echo \$errortext;
}
?>
</form>

``````

You know Im nearly nearly there I can feel it…!!

Once again greatest thanks is handed out to you in copius amounts, it really is starting to make sense.

True and false in a function seem to work well when using if and else statements (basically you can use true and false when the code sequence can be affected by the user)

If I want to run some sort of pattern like addition or a sequence that should’t be interupted, (something definate if you like) although the values can be changed if I want, it seems I would just return the function name.

Also I can write a function using false if I predict that the user is gonna do something and its something I don’t want them to do…?

And its good not to return anything when using strings or displaying the result of perhaps another function., as there is nothing to do in the code.

If Im totally off the mark then its time for me to go and beat up the local cow, but although it might not seem like it, things do seem to be getting a bit clearer.

I don’t know if you’re off mark, since I don’t understand what you mean by the parts I marked in red (yeah I know, almost everything, sorry).
Could you give some concrete examples? In code if possible, in plain english if not.
I’m still having the feeling that you’re confusing between user functions (where the user is you, not the user of your site, it’s functions written by you) and php functions.

lol I haven’t seen that much red pen since school, ok Ill try again, sorry

Code nature of using true and false. This type of code is kinda like saying “if you do what I want you get a tick, but if not you get a cross and you gotta do it again.” It also shows how the user can affect the result returned.

``````
function isDigit(\$str) {
if(indexOf(\$str, '0123456789)) // simple way to test
return true; // it is a digit
else
return false;
}

``````

This bit of code is saying, “this is the challenge, no questions, just do it, although answer it how you will.”

``````
function displayError(\$string) {
echo '<p class="error">' . \$string . '</p>';

``````

This bit of code is like saying "you can paint the house with whatever color you want but make sure you paint the walls in this order

``````
function AddThese (\$first, \$second, \$third)

{
//this is what the function actually does, what happens inside it.
\$answer = \$first + \$second + \$third;

}
//this part is to do with Add these function
\$first = 5 ;
\$second = 34 ;
\$third = 237 ;
\$math = AddThese(\$first, \$second, \$third) ;
echo "\$first,  \$second, and \$third add up to: " . \$math ;

``````

And finally this one is saying “ok Ive paid for my pizza now time to go and pick it up.”

``````function Mytestfunction ()
{
echo "This is being shown as the function has now been defined"
}

Mytestfunction(); //function activated or called

``````

The more I simplify things and relate it to logic I understand I seem to be able to get further. thanks again guido

No it is not. The function definition (given below ), is saying
“if you give me a digit, I’ll return true, but if you don’t give me a digit, I’ll return false”. That’s the isDigit function definition. No going and doing it all again or any other thing, just a very plain very clear “if its a number I’ll say true and if it ain’t I’ll say false”.

No again wrong way of looking at it. The programmer might use the isDigit function to say, check a telephone number is all digits. So she might set her program to walk through each individual number in the telephone number and check it’s a digit. ( Possibly not the most efficient way to do this particular task but it suits for an example.)

So the programmer might write something like this

``````
\$i=0;
while ( isDigit(\$telephonenumber[\$i]) ) i++;
if (\$i != strlen(\$telephonenumber)) {
// process telephone number is bad
//
} else {
// process  telephone number is okay

}

``````

That is nothing to do with an end user. What’s happening is a programmer is using the isDigit function. The programmer may be wbriting a program to verify a telephone number input by a user or her program may be a utility to check some database values.

---------------- end of isDigit function discussion ----------

Ermm again I am going to say no :).

The function definition for displayError displays the contents of \$string to whatever media standard output refers to - be that braille printer, screen or screen reader.

So a programmer sends a string to the displayError function and the displayError function will display it. The name of the function gives a reasonable idea what the displayError function should be used for.

There is no challenge going on anywhere - just a task being performed.
And there is no response to assure the programmer everything went okay or if it failed.

Nope - no house - no paint - no colours - no walls - just another function definition - this time for the AddThese function.

Guess what ? Nope - no pizza there either !!!

Just wait now, what could it be? … oh, another function definition.!!! Wow!

I’m not sure what logical framework you think you are using but it really isn’t working.

Sometimes you need a function to return a value and sometimes you don’t. You can always call a function and disregard its return value if you want to.

Please avoid relating what’s happening in a program to anything else you understand in life. It isn’t helping you form a clear view. It is, in fact, obscuring everything for you.

Also please note that functions return values. This has already been pointed out by another poster. A particular type of function, called a recursive function, may well return itself, but that is a more advanced problem and far too advanced for you while you insist on obscuring the facts for yourself.

Try not to complain about the terminology until you understand it. Learn the terminology so you can talk to people who program and talk to each other about it. Leave the pizzas, house painting and other marvellous wonders outside the door. If one thing appears to be saying the same as another then it may be so or it might not be - it might be you are missing a subtle but significant difference and your mind is too busy attempting to relate it all to the price of silk to work out what that difference might be.