Functions are an important part of programming languages. They help us avoid code duplication by allowing us to run same set of instruction over and over again on different data.
In this tutorial, we will talk about functions in PHP. We will cover all the basics concepts of functions in PHP. This tutorial will teach you how to create your own user-defined functions in PHP. You will learn about return values from a function and function parameters in PHP. You'll also learn other concepts like setting default argument values or passing an argument by reference.
Internal Functions in PHP
PHP comes with a lot of built-in functions that you can use in your program. Some of these functions come with PHP as standard while others become available to you through specific PHP extensions.
PHP comes with a lot of functions to work with strings. For example, you can use the str_contains()
function to check if a string contains a substring and wordwrap()
function to wrap wrap a string to given number of characters. These functions are available for you to use as standard.
Another set of PHP functions to manipulate images are available if you install the GD extension library. Once the extension is enabled, you will be able to use functions like imagecreatetruecolor()
, imagecreatefrompng()
and imagefill()
to create and manipulate images.
If you ever get a fatal undefined function error in PHP but you are certain that it is an internal function, make sure that you have installed the respective extensions to use that function.
User Defined Functions in PHP
You can also define your own functions in PHP. Defining your own functions becomes a necessity in almost every non-trivial program you write. They are a great way to avoid code duplication and errors.
Here is some basic code to define a function that outputs a greeting when we call the function later.
<?php function greet($name) { echo 'Hello '.$name.'!'; echo 'Your name as '.strlen($name).' letters.'; } greet('Andrew'); // Hello Andrew! // Your name as 6 letters. greet('Adam'); // Hello Adam! // Your name as 4 letters. ?>
In the above example, we just passed a name to the greet()
function and it echoed different output based on the specified name.
You have to follow specific rules when defining a function. The name of a function has to start with a letter or an underscore. After that, you can use different length of numbers, letters and underscores in the name. This means that greet01()
, _greet()
and greet_01()
are all valid function name in PHP. However, using 01_greet()
as a function name will throw a syntax error.
Return From a Function in PHP
In the previous example, our user-defined greet()
function did not return anything. It just echoed a couple of sentences based on the input. It is entirely up to us to return anything back inside any function we define in PHP.
When you want to return something, you need to use the return statement. A function can return any type of value in PHP. This includes strings, integers, floats, arrays or even objects.
<?php function palindrome($word) { return $word.strrev($word); } $apple_palindrome = palindrome('apple'); // appleelppa echo $apple_palindrome; ?>
In the above example, the palindrome()
function turns any given string into a palindrome by appending it to its reversed version. Now instead of echoing the output directly, we assign it to a variable. We can now further manipulate the variable but just echo it in this example.
A function can have multiple return values and the execution of the function stops immediately once it encounters a return
statement. This means that you can only return one value from a function. However, you can work around this limitation by returning an array that consists of all the values that you want to return as its elements.
<?php function greet($name) { echo 'Hello '.$name.'!'; return [$name, strtoupper($name), strlen($name)]; echo 'Bye '.$name.'!'; } list($name, $capital_name, $name_length) = greet('Monty'); echo 'Your name is '.$name.'.'; echo 'Your name is '.$capital_name.' in capitals.'; echo 'Your name is '.$name_length.' characters long.'; /* Hello Monty! Your name is Monty. Your name is MONTY in capitals. Your name is 5 characters long. */ ?>
In the above example, we wanted the function to return a bunch of information about the name passed to it. So, we used an array with mixed values. The passed values are then assigned to different variables using list()
.
You should also note that the greet()
function did not echo Bye Monty! in our program. This is because the function execution was stopped as soon as it encountered a return statement.
Function Parameters in PHP
Function parameters (also known as "function arguments") are used to pass input to a function upon which it can act to give us the desired output. We have only defined functions with a single parameter so far in this tutorial.
However, it is entirely up to us how many parameters we want to pass to a function. It can be zero for functions which don't require any kind of input from us. It can also be two, three, five, or ten. You can also pass arrays as parameters.
Here is an example of PHP functions that accept zero and two parameters respectively.
<?php function day_date_time() { echo 'Today is '.date('l'); echo 'The date is '.date('d F, Y'); echo 'The time is '.date('h:i:s A'); } day_date_time(); /* Today is Monday The date is 15 February, 2021 The time is 03:11:17 PM */ function greeting_time($name, $time) { echo 'Good '.$time.', '.$name.'!'; } greeting_time('Adam', 'morning'); // Good morning, Adam! ?>
We can rewrite the second function to pass an array as our only parameter. We will just extract different values from the array inside our function. This can be helpful in situations where you want to either manipulate arrays or pass a lot of values to a function.
<?php function greeting_time_arr($input) { list($name, $time) = $input; echo 'Good '.$time.', '.$name.'!'; } greeting_time_arr(['Andrew', 'morning']); // Good morning, Andrew! ?>
Specifying Default Argument Values
Let's say you create a greeting function that is mostly used to wish users good morning. The value of $time
in our greeting_time()
function will usually be morning then. In such cases, you can make the your program shorter and code easier to read by assigning sensible default values to specific arguments.
This is actually quite common in built-in PHP functions. The strpos()
function is used to find the location of a substring in a string. The function takes three arguments: the string, the substring, and the position where you want to start. The function returns the index of the substring in the string.
The position parameter is the pooint at which you want to start looking for the substring. Usually, we want to look inside the main string from its starting position. This means that the value of offset will usually be zero.
Instead of asking us to specify the offset as 0 each time we call the function, PHP sets it value to 0 by default. Now, we only need to specify the third parameter when we want to change the offset to something else.
We can also set a default value for different parameters in our own functions. Here is an example:
<?php function greeting_time($name, $time = 'morning') { echo 'Good '.$time.', '.$name.'!'; } greeting_time('Monty'); // Good morning, Monty! greeting_time('Monty', 'evening'); // Good evening, Monty! ?>
There are two things that you need to keep in mind about default parameters or arguments. First, they have to be a constant value like morning in our case. Any arguments with default values should always be on the right side. For example, the following function definition will cause an error during the first call.
<?php function greeting_time($time = 'morning', $name) { echo 'Good '.$time.', '.$name.'!'; } greeting_time('Monty'); // Error ?>
The reason for the error is the ambiguity about the argument Monty. PHP has no way of knowing if you want it to be the value of $name
or if you want to use it in place of default $time
value.
Passing Arguments by Value vs Passing by Reference
By default, different arguments are passed to a PHP function by value. This way we can avoid changing the value of the argument passed to a function. However, if you intend to change the value of arguments passed to a PHP function, you can pass those arguments by reference.
The following example should help you understand the difference between these two approaches.
<?php $word_a = 'apple'; $word_b = 'mango'; function v_palindrome($word) { $word = $word.strrev($word); return $word; } $palin_a = v_palindrome($word_a); echo $word_a; // apple echo $palin_a; // appleelppa function r_palindrome(&$word) { $word = $word.strrev($word); return $word; } $palin_b = r_palindrome($word_b); echo $word_b; // mangoognam echo $palin_b; // mangoognam ?>
The argument in r_palindrome()
is passed by reference. This means that when we pass $word_b
to r_palindrome()
the value of $word_b
itself is changed to a palindrome.
Conclusion
In this tutorial, we have covered a lot of basics related to functions in PHP. Hopefully, you can now write your own user-defined functions that take advantage of everything we learned here. Feel free to ask any questions you have about this topic in comments.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
-
FREEPHPPHP Fundamentals
No comments:
Post a Comment