PHP: User defined Functions

There are many functions provided by PHP like array(). But the users can define functions of their own. A function in PHP has the following form

function functionName(functionArguments) {
   // Body of the function
   // optional return value

Take for example, we want to create a function to convert an array of strings to upper case using the function strtoupper() provided by the PHP.

function changeToUpperCase($stringArray) {
    for($i=0 ; $i < sizeof($stringArray); $i++) {
        $stringArray[$i] = strtoupper($stringArray[$i]);
$days = array("Sunday", "Monday", "Tuesday", "Wednesday",
 "Thursday", "Friday", "Saturday");


Here we can see the function changeToUpperCase being defined. It takes only one argument which is an array (of strings), changes the case of the array elements and finally prints the array using another PHP function var_dump().

The output

array(7) {
  string(6) "SUNDAY"
  string(6) "MONDAY"
  string(7) "TUESDAY"
  string(9) "WEDNESDAY"
  string(8) "THURSDAY"
  string(6) "FRIDAY"
  string(8) "SATURDAY"

The advantage of using functions is to make the program modular and readable and to avoid rewriting code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s