In this tutorial we are going to learn about functions in PHP those are same as in javascript. We are also going to learn about the use of include and require keywords in this PHP Functions tutorial.
Let us start with user defined functions.
- Create a new folder named Functions in the htdocs folder in the xampp folder in C drive.
- Open a new notepad++ document and save it as index.php in the newly created Functions folder in the htdocs folder.
- Write the following code for a simple function:
- This is a simple function written to display Hello on the browser.
- In PHP the keyword function is used to define a function name.
- The keyword function is followed by a function name with parenthesis.
- The naming convention followed in function name is that starting word of function name is in small case letters and the initial letter of the following word is capital.
- The opening and closing curly braces forms the body of the function.
- The body of the function contains the code to be executed.
- Here, echo statement to display a word Hello is used.
- The opening curly brace indicate the start of the function and the closing brace indicate the end of the function.
- Writing just the function definition would not display anything on the browser. To execute a function it should be called.
- Write the following code below the function definition:
- To call any function you just have to write its name with parenthesis.
- When a function is called, it gets executed and the output is shown.
- Let us see the output on the browser. Open your browser and write localhost/Functions in the address bar of the browser.
- Now let us go for a parameterized function. Write the following code in index.php file.
- You can drop the ?> delimiter of php tag.
- Here, in the sayIt function one parameter $word is passed. And its value is printed in the function body using echo statement.
- The value for the parameter $word is passed through function call.
- So write the sayIt() function call statement below the function definition as shown below:
- The output after the function call is shown below:
- Now let us see function with multiple parameters. Write the following code in index.php document:
- We have a sayAll() function with 2 parameters $word1 and $word2.
- The body of the function contains the echo statement that displays the values of the two parameters concatenated with a space.
- The function is executed when it is called. The function call statement is shown below:
- The value Hello in the above function call will be assigned to parameter $word1 and value Brad will be assigned to parameter $word2.
- The output after calling sayAll() function is shown below:
- Now instead of 2 parameters if we pass only one parameter value to the sayAll() function as shown below:
- And then reload the browser, it will display Hello but also a warning for the missing second parameter as shown below:
- To avoid this type of warning we can provide the function parameter with a default value as shown below:
- Here we have given a default value World to the second parameter $word2.
- Now if we call the above function with a single parameter as shown below:
- The value Hello will be assigned to parameter $word1 and as there is no second parameter provided, the parameter $word2 will take the default value World and Hello World will be displayed as shown below:
- If we call the sayAll() function with 2 parameters as shown below:
- The value Hello will be assigned to $word1 and value Bob will be assigned to $word2 overwriting the default value World and the function will display Hello Bob.
- Now let’s try a mathematical function for addition of 2 numbers.
- Write the following code in index.php document.
- Here, we have a two parameterized function displaying addition of 2 numbers.
- The function call is shown below:
- The value 7 and value 2 in the function call will be assigned to $num1 and $num2 function parameters respectively.
- These values are numbers hence not placed in single/double quotes.
- A string Addition of 2 numbers is concatenated with the addition.
- The output of addition is shown below:
- In the above add() function we have directly printed the output in the function itself using echo statement.
- But it is not a good practice. I mean if we don’t want to print the value and just want to store it for some other use, then.
- The return statement is the solution. Instead of echo use return, it will return the calculated value to the function call statement.
- Modify the above add() function in the way shown below:
- Now write the function call statement below this function as shown:
- After calling the add() function the addition of values 10 and 5 will be returned from the function and stored in the variable $sum. You can now display it using echo statement or can use it for some other calculation purpose.
- We have displayed the addition. Output is shown below:
- Now let us learn a new topic of linking one PHP file to another.
- To link one PHP file to another we use keywords include and require.
- Now go to the Functions folder in the htdocs folder and open a new notepad++ document. Save it as functions.php.
- Write the add function in this file functions.php as shown below:
- Comment the whole add() function in the index.php document.
- Keep the function call to add() function uncommented.
- Now you don’t have the function body for add() function in index.php file but you have a call for the function.
- Reload the browser and you will get an error saying “call to undefined function add()” as shown below:
- This is because body for function add() is not written in index.php document.
- Since this function is written in functions.php file, we can link this file to index.php to resolve this problem.
- Write the following code inside the tag at the top to link the functions.php file to index.php file, in the index.php file.
- Actually the uncommented code in index.php file will be only this much:
- Now reload the browser and see the output:
- In the above linking code we can also use require or require_once keyword instead of include.
- The code for it is shown below:
- OR
- Both include and require keywords do the same work but the only difference between them is that,
- If you use include keyword to link one file with another and any error occurs in linking the file, you will get an error message for the file linking; but the rest of the code that does not require the file will work properly.
- Next if we use require keyword to link the file and there is some problem in file linking, all the code along with the code that does not require linked file will stop working.
- To demonstrate the difference between the include and require keywords let’s do some task:
- Replace the function call to add() function in index.php file with the following statement:
- Replace the function body in functions.php file with the following statement:
- We have used include keyword in index.php file to link functions.php file with it.
- So now reload the browser and see the output:
- Now just purposefully make a mistake in the linked filename in index.php file as shown below:
- This will invoke a warning saying “failed opening functions1.php” but at the same time it will display the statement “I am in index.php” which has nothing to do with the linked file as shown below:
- Now just replace include keyword with require keyword in the index.php file as shown below:
- Remember we had made a mistake in the linked file name i.e. instead of writing functions.php we have written functions1.php.
- Now reload the browser and view the output:
- Here, when you use require keyword we get a fatal error and the statements that do not require the file are also not executed.
- Hence, it is mostly good to use include keyword instead of require.
- Now let us go for some inbuilt functions and understand them.
- str_replace() function:
- The task of str_replace() function is to replace a string or word in a phrase/sentence with the specified string.
- Syntax of the str_replace() function is :
- In the above syntax: old string indicate the string in the sentence which is to be replaced, new string indicate the string to be placed in the old string’s position and statement is the sentence in which this replacement is to be done.
- Let us demonstrate it with an example. Write the following code in index.php file:
- Here, we have a sentence “I like to eat apples.” in a variable $phrase which is displayed using echo under the heading “Before replacement”.
- Next we have used the str_replace() function to replace the word apples with oranges and displayed the sentence again under the heading “After replacement”.
- You will see in the output that after replacement the word apples have been replaced with oranges. Output is shown below:
- print_r() function:
- This function is used to print the entire array in the browser.
- Let us see an example. Write the following code in index.php file:
- This function print_r() will display the array in the form of index=>value pair. Output is shown below:
- implode() function:
- This function deals with arrays.
- Its purpose is to display an array directly in a string format.
- If we try to display it directly using echo it will give an error.
- Suppose I try to display the array $name_array declared in the above code example for print_r() function as shown below, it will give an error:
- After reloading the browser you will notice the array to string conversion error as shown below:
- To resolve this problem we need to use implode() function which converts the array to string and gives us the string output of array.
- Syntax of implode() function is :
- Here, separator indicate a delimiter like comma, period, semi-colon, brake tag, space etc to separate the array elements.
- And array_name indicate the name of the array whose elements are to be displayed in the form of string.
- Let us see one example. Write the following code in index.php file.
- The function implode() will take all the array elements and use comma as the separator and store it in the variable $name_string which is then displayed using echo.
- The output is shown below:
- explode() function:
- The function explode() is the opposite of implode().
- It does the work of converting a string into an array.
- To demonstrate it let us try an example. Write the following code in index.php file:
- Here, a variable $car_string contains a string of names of cars separated by comma.
- We have used explode() function to convert it into an array.
- Syntax of explode() function:
- Here, separator indicates a delimiter that is used in the string to separate the elements in the string.
- And string indicates the name of the string that is to be converted in to an array.
- The explode() function considers each element separated by a comma in this case as one element and gives each element an index and then stores the array formed in a variable $car_array.
- It is then displayed using print_r() function.
- The output is shown below:
- Some other inbuilt functions:
- ucwords() function:
- This function is used to convert the lower case initial letters to capital letters.
- Write the following code in index.php:
- The output is shown below:
- strtolower() function:
- This function is used to convert all the lower case letters in a string to upper case letters.
- Write the following code in index.php:
- The output is shown below:
- count() function:
- This function counts the number of elements in a given array.
- Write the following code in index.php file:
- The array $name_array contains 5 elements that will be counted using count() function.
- The output is shown below:
- sort() function:
- This function sorts the given array alphabetically.
- Write the following code in index.php file:
- Here, we have declared an array $car_array. Elements are not arranged alphabetically in it. Using sort() function we will arrange them alphabetically.
- And print_r() function is used to display the array.
- The output is shown below:
<?php function sayHello() { echo 'Hello'; } ?>
sayHello(); //call to sayHello() function
<?php function sayIt($word) { echo $word; }
sayIt('Hello World');
<?php function sayAll($word1,$word2) { echo $word1.' '.$word2; }
sayAll('Hello','Brad');
sayAll(‘Hello’);
<?php function sayAll($word1,$word2='World') { echo $word1.' '.$word2; }
sayAll(‘Hello’);
sayAll(‘Hello’,’Bob’);
<?php function add($num1,$num2) { echo “Addition of 2 numbers = ”.($num1+$num2); }
add(7,2);
function add($num1,$num2) { return $num1+$num2; }
$sum=add(10,5); echo 'Addition = '.$sum;
<?php function add($num1,$num2) { return $num1+$num2; }
include 'functions.php';
<?php include 'functions.php'; $sum=add(5,5); echo 'Addition = '.$sum; ?>
require ‘functions.php’;
require_once ‘functions.php’;
echo 'I am in index.php';
echo 'I am in functions.php <br/>';
include ‘functions1.php’;
require 'functions1.php';
str_replace(‘old string’,’new string’,’statement’);
<?php $phrase="<h1>I like to eat apples.</h1>"; echo 'Before replacement:'; echo $phrase; $phrase=str_replace('apples','oranges',$phrase); echo 'After replacement:'; echo $phrase;
<?php $name_array=array('Brad','Bob','Mike','Sarah','Michelle'); print_r($name_array);
echo $name_array;
implode(‘separator’,array_name);
<?php $name_array=array('Brad','Bob','Mike','Sarah','Michelle'); $name_string=implode(',',$name_array); echo $name_string;
<?php $car_string='Toyota,Ford,Dodge,Nissan,Kia,Mazda'; $car_array=explode(',',$car_string); print_r($car_array);
explode(‘separator’,string);
echo ucwords('hello world');
echo strtolower('HELLO WORLD');
$name_array=array('Brad','Bob','Mike','Sarah','Michelle'); echo 'No. of elements: '.count($name_array);
$car_array=array('Toyota','Ford','Dodge','Nissan','Kia','Mazda'); sort($car_array); print_r($car_array);
Thus we finished learning user defined functions, linking two PHP files and some built-in functions in this PHP Functions tutorial.