User-Defined Functions in PHP and Returning Multiple Values

There are a lot of in-built functions in PHP. We have seen several of those already. We talked about string functions like strpos() and mathematical functions like pow(). There is a long list of these in-built functions.

But the beauty of functions do not end there. Programmers can create their own functions to perform custom tasks. If you have to perform the same calculations again and again, they reduce the number of lines in a code. You can instead call functions multiple times and negate redundancy.

Simple Function in PHP

This is a function created without any arguments or return values.


Functions with Arguments

Functions can take in arguments which it can process within the function. If a default value for those arguments is not specified in the function declaration line, then you will have to enter values to pass in the argument. If you want to pass nothing, then still you’ll have to write NULL or “”.


Note: Although in the example we only take in one argument, the number of arguments a function can take are not limited.

Default Values of Arguments

You can also set the default values of arguments so as to use them if the argument is not provided.


Functions with Return Values

Instead of directly printing the output from a function, you can return the value from the function. Then you can assign the value to a variable or print it directly.


Dealing with Multiple Values to Return

You cannot use two variable to return multiple values from a function. But what you can do is use arrays for returning multiple values.


You may also like

Comments are closed here.


Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers