PHP Lessons 7: Functions in PHP

by
Guest-GS

Ok guys and girls, this is lesson 6 and I hope we can at least get to lesson 100! 😀

Today we will have a look at functions in PHP. First, what’s a function? It’s simply a sort of container for code. Whenever you call the function, the code inside gets executed. Also, functions can accept parameters, which are values that the function needs to work. If you remember a bit of your maths, “cos x” is a function, and x is the parameter or argument. Usually the result you get by doing the cosine operation is the return value. Just remember those terms for later.

PHP provides us with a lot of built-in functions which make our life easier and also speed up our projects. But sometimes, you have code you wrote and you want to be able to access those code on another pages. You would say, well, I can copy and paste the code on the supposed page or paste it whevever I need but really, this isn’t a good PHP approach, nor good programming approach in general. So, a good thing to know is that PHP allows us to write our own functions which we programmers call ‘User Defined Functions’.

First of all, I won’t be listing any built-in function in this lesson since there are tons of them. And you can’t possibly know all of them by heart nor can we list them all here. You can go to the link below and have a look at all the built-in function PHP provides. Bookmark that page, it’s great reference material.

PHP Function Quickref

Ok, moving on to our topic- today I will show you how you can write your own functions.

The syntax is like this:

<?php

  function function_name(){
      //put codes here
  }

?>

Let’s analyze this, when writing a function, you should ALWAYS start with the word ‘function’ (without the single quotes). What comes after the word
“function”, is simply the name of you function. It could be anything except Numbers and can’t contain spaces. After the name of your function, you put the brackets, then your curly braces.

Note: In the braces right after your function name, you can pass in arguments. We will cover those later in this lesson.

Instead of using function_name as the name of my function, i could have named it ‘geekscribes’, like below

<?php

  function geekscribes(){
      //put codes here
  }

?>

But remember to always use meaningful names for your function! This is PRIMORDIAL if you want to become a good programmer. Because nobody can guess what “function xyz()” will do, but “function avgcalc()” makes more sense. Since we are at naming functions, there are some conventions you might want to follow. No convention is forced upon you, so just choose the one you like and stick with it. And please, I mean STICK WITH IT, so don’t change along the way when you are coding. Just keep a standard.

Function names usually won’t have spaces. Numbers and underscores are accepted, but their usage is discouraged. Functions should be camelCased, that is the first letter of the first word lowercase, the remaining words’ first letters uppercased. For e.g. “function getInput()” is appropriate. You could have written “function get_input()” too. That’s what I meant by choose a convention and stick with it. I usually use the first one, “getInput()”.

So, how do I use a function?

Below is a little example:

<?php

  function geekscribes(){
      echo "I'm a website";
  }

?>

To run this code, write it in a file, save it as “file.php” or something, it should end in “php” though. Put it in your webserver root, “www”, “public_html” or whatever, start your server and access it. Eg. “http://localhost/file.php”. Tada, blank page! Huh wait, something must be wrong? Nope, it’s totally correct. What just happened then?

Well, the answer to that is: When you write a function, it won’t do anything good unless you call the function. How do we call the function, below is an example:

<?php

  function geekscribes(){
      echo "I'm a website";
  }

  geekscribes(); // we call the function like this

?>

Run this code now, you will see ‘I’m a website’ on your screen.  You call functions simply by writing the “function_name()” part followed by a semi-colon, in this case “geekscribes();”. Don’t put the “function” part in front. You put “function” in front when you are declaring a function, not when calling.

Well, this is just a basic example of function and this is actually the wrong approach of using function. Why? Because we are echoing our values directly in the function which is considered BAD practice. Well, you might say, how the hell will I get something on the screen if I don’t use the echo? Well, you can use the ‘return’ keyword. Ok, let’s have an example below:

<?php

  function geekscribes(){
      return "I'm a website";
  }

  echo geekscribes(); // we call the function like this

?>

You echo what the function returns, i.e. it will return the string “I’m a website”. Return is like the function is sending back something to wherever it was called.

Always remember, do NOT echo stuff directly into your function. This is considered BAD practice. Use the word ‘return‘ then, just place an echo before calling your function back. Oh, not all functions return values. Some may just do some operation silently, but it’s good practice to return a value to indicate if the operation was successful or it failed. It makes checking for errors easier.

An important point to note: The return statement/line marks the end of the function. Whatever code you place after the return does not get executed. It’s as if, when return is encountered, the function immediately exits, returning whatever value it needs to return. This mechanism can be useful in a number of ways, e.g. checking for a range of values, and returning “false” if an input is outside the valid range, or doing some operation and returning the good result if the range was respected.

There are some questions you might ask. Like, “In what way will function help me?”

Well, assume you are working on a project with a database, you will have to connect to the database first, so instead of typing the same thing on and on, you could just wrap it in a function and call that function anytime you want to make a connection to the database and query out some stuff. In other words, it’s useful if you need to do a task several times, at different points in time. Ok, some of you might be wondering what is this “database” connection thing. Patience! It will come later in another lesson.

Back to our function lesson.

We now know how to write a function. Let’s have a look at how we can pass arguments to our function.

Remember I told you earlier that we can pass arguments between the braces, right after the function name? Below is an example of how it is:

<?php

  function geekscribes($args){
      //put codes here
  }

?>

As you can, the function now take one arguments. which i called $args. It’s just a variable. Nothing more. Really simple. If you want to pass in more arguments, just put a comma after the variable $args and write another variable there. Just comma-separate all the variables you want to pass in, like so:

<?php

  function geekscribes($args, $another_args, $yet_another_args){
      //put codes here
  }

?>

But for the sake of this lesson, let’s keep this simple. Let’s see how we can get the function to work with an argument.

<?php

  function geekscribes($msg){
      return $msg;
  }

  echo geekscribes('Hey how are you doing? Any php lesson for today?');

?>

Let’s break this down. Our function takes one argument, which I called $msg (it makes more sense since I’m going to output a message. Good naming practices, kids, remember!). Between my curly braces, I just wrote:

return $msg;

What it does is return whatever message I will pass to that function when calling it. As you can see in the code above, i wrote

echo geekscribes('Hey how are you doing? Any php lesson for today?');

The message “Hey how are you doing? Any php lesson for today?”, is the parameter our function will take. Remember that when passing parameter to the function, it should be between quotes. Single quotes or double quotes. Usually, we use single quotes, unless the text has apostrophes inside. Then only, use double quotes, since single quotes would mess everything up. Eg. ‘I’m a website’. PHP thinks that what you want to pass in is “I”, and then finds an unclosed quote after website, and it goes “WTF?” and crashes.

If we didn’t put something between the quotes when calling our function, we would get that error:

Warning: Missing argument 1 for geekscribes()

What it means is that PHP was expecting an argument (or more), and you didn’t supply one (or more). Poor thing was sad, and wants you to know it. Hope that makes sense!

Now a little technique that can be use to avoid getting such ugly error messages when calling function is like below:

<?php

  function geekscribes($msg=''){
    if(!$msg){
        $msg = 'This is a default text';
    }

    return $msg;
  }

  echo geekscribes().'<br />';

  echo geekscribes('Hey how are you doing? Any php lesson for today?');

?>

As you can see, our argument $msg is a bit different. We just assigned it to nothing. Which means, it can be optional when calling our function.

Let’s break the code above. We start by writing our function:

<?php

  function geekscribes($msg=''){

  }

?>

In our function, we use our good if statement to check if the argument message is empty. Of course it will be empty, since we wrote $msg = ”.

If it is empty, then we will set the $msg variable to “This is a default text”, otherwise, just return the $msg variable.

<?php

  function geekscribes($msg=''){

    if(!$msg){
      // if the variable $msg is empty, just give it a default text
      $msg = 'This is a default text';
    }

    //return the variable
    return $msg;

  }

  // Will output "This is a default text" since we didn't pass
  // in any message when echoing the function
  echo geekscribes().'<br />';

  // Below will output "Hey how are you doing? Any php lesson for today?"
  // Since we gave it that sentence to output
  echo geekscribes('Hey how are you doing? Any php lesson for today?');
?>

Now, a little tip, have a look at our if statement in the function, we wrote if(!$msg). Instead of using the ! operator, let’s use a built-in function called empty(). Homework: Investigate the isset() function too. Have a look below:

<?php

  function geekscribes($msg=''){

    if(empty($msg)){
        // if the variable $msg is empty, just give it a default text
        $msg = 'This is a default text';
    }

    //return the variable
    return $msg;

  }

  //The line below will output "This is a default text"
  //since we didn't pass in any message when echoing the function
  echo geekscribes().'<br />';

  //The line below will output "Hey how are you doing? Any php lesson for today?"
  //since we gave it that sentence to output
  echo geekscribes('Hey how are you doing? Any php lesson for today?');

?>

It will work fine, just as with the (!$msg) one. Just remember that you need to make sure you close your braces else you will get an ugly error. Example below:

if( empty ($msg) )

Another quick tip, remember the Ternary Operator we talked about in the Operator lesson? Let’s use this to return our variable.

<?php

  function geekscribes($msg=''){
      return empty($msg) ? 'This is a default text' : $msg;
  }

  echo geekscribes().'<br />';

  echo geekscribes('Hey how are you doing? Any php lesson for today?');

?>

It basically means, if $msg is empty, return ‘This is a default text’, else return $msg that was passed itself.

Hope you get the idea. Try those on your own. If you’re stuck, comments are open below. Just drop some words and we will get to you.

This article was contributed by Tipa of Mu-Anime

[seriesposts title=”PHP Lessons” titletag=h3 listtype=ul orderby=date name=”PHP Lessons” ]

  • really nice article, continue for class in PHP? 😀 thx for sharing

  • InF

    We will, but for now, we are slightly busy with university stuff. We’ll continue soon.

    Thank you for your patience.. 🙂

  • ok nice¡¡¡ thx master 🙂

  • Hi, Geeksscribes

    Any free ebook to offer for php lesson that used in wordpress like how to use tag,etc

  • InF

    How to use tags? You mean, how you can code themes and plugins? Cuz I didn’t totally understand your question.

    The PHP used in WordPress is the same as with any other sites. It’s just that WordPress has its own API that facilitates coding stuff for it, for example, the Posts loop. It’s to facilitate your coding themes and other tasks that require retrieving posts. Other such functions exist.

    About PHP, you can find good books online, such as PHP in a Nutshell if you have some basic programming knowledge. Or Sams Teaches You PHP is very good too. PHP is a relatively easy language to learn.

    After you have a solid PHP foundation, check the WordPress Docs (Codex) to know more about the API and started coding. Once you know PHP, learning the WordPress API should take a couple of days at most, and there exists some very good quick-references.

    Do try these and let me know! 🙂

  • stiofan

    Love your php lessons, very easy to understand, infact the easiest i have found! only concern is there is a few mistakes in ur code and spelling, you would benifit from reading over them all again. but still the best, i want more!!

  • InF

    Please point out any mistakes you find, and we’d be happy to amend! 🙂

    Thanks a lot for reading.