PHP Functions

0
1572

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.

  1. Create a new folder named Functions in the htdocs folder in the xampp folder in C drive.
  2. Open a new notepad++ document and save it as index.php in the newly created Functions folder in the htdocs folder.
  3. 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.
    • output_of_simple_func_sayHello
      fig 1

  4. 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:
    • output_of_1_parameterized_func
      fig 2

  5. 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:
    • output_of_2_parameterised_func
      fig 3

    • 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:
    • missing_parameter_warning
      fig 4

    • 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:
    • default_parameter_output
      fig 5

    • 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.
  6. 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:
    • output_of_add_func
      fig 6

    • 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:
    • return_stmt_output
      fig 7

  7. 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:
    • error_because_of_absence_of_function
      fig 8

    • 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:
    • output_of_linking_using_include
      fig 9

    • 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.
  8. 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:
    • include_demonstration
      fig 10

    • 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:
    • include_demonstration_error
      fig 11

    • 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:
    • require_demontration_error
      fig 12

    • 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.
  9. Now let us go for some inbuilt functions and understand them.
    1. 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:
      • str_replace_function_output
        fig 13

    2. 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:
      • print_r_func_output
        fig 14

    3. 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:
      • array_to_string_conversion_error_output
        fig 15

      • 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:
      • implode_func_output
        fig 16

    4. 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:
      • explode_func_output
        fig 17

  10. Some other inbuilt functions:
    1. 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:
      • ucwords_func_output
        fig 18

    2. 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:
      • strtolower_func_output
        fig 19

    3. 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:
      • count_func_output
        fig 20

    4. 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:
      • sort_func_output
        fig 21

Thus we finished learning user defined functions, linking two PHP files and some built-in functions in this PHP Functions tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here