A function is used in almost every programming language to reduce excessive code and for effective code re-usability. In some programming languages function is called as method. In almost every programming language they’re used to perform particular task on regular basis. This way it saves time of programmer and code also becomes more readable.
In this tutorial we’re going to take a look at function syntax and various ways to use functions.
Syntax
<?php function name_of_function() { } ?>
You can follow camel-case convention for the function name. You can also use underscore for the function name but never start it with number or else compiler will flag error.
Keep these points in mind while writing functions –
- Start your function with the keyword function.
- Function should be declared first before using in your program.
- Make sure the function name is correctly used in a program.
How to Use PHP function
We have already created our first function so let’s take a quick look at how we can use it in our program. One thing to note that you have to declare the function before you use it. You can also add the function by import function if you want in your program.
<?php function hello(){ echo "hello"; } echo "this is function demo"; echo "<br/>"; hello(); ?>
Parametrized Functions
You can pass value to your functions from outside the functions. You can then use the value to process in your function or just use them to print out on web page.
<?php function apple($num){ echo "no of apples are". $num . "<br/>"; } apple(12); ?>
You can also process the value and show results back to the user.
<?php function apple($num){ $num+=1; echo "no of apples after adding 1 more in the basket :". $num ."<br/>"; } apple(12); ?>
That’s it. You now know how to use functions in php. You can practice using functions with some demo programs. There are many home work assignments out there that you can see for more php function examples. Hope this helps you. Feel free to ask questions, suggest a feature, point errors. Don’t forget to bookmark or share this site in any social network site of your choice.