Defining functions in php

In our last lesson, we set our local computer up to operate php and created a simple script. In this lesson, we are going to cover defining a basic function.

First we will start with functions. In php, we are able to define a function that will make it simple for us to call that again and again without having to enter it over and over. In a few of my scripts, I use a seo friendly way to make urls appear. To do this on multiple pages of the script, I use a functions.php page to load the function. The function uses a php command that is predefined: str_replace.

The str_replace function allows you to enter a string that you want to replace with a new string out of a particular variable. The command looks like this str_replace(‘What I want to get rid of’,'What I am replacing it with’,$variable);. See the code below for demonstration.

Open your php editor and create a new file. We will save this as home.php.

<?php
//We will first need to define a variable
//Remember last time how we learned the comment out section?
$string = "Fuzzy Wuzzy was a bear, Fuzzy Wuzzy had no hair, now Fuzzy Wuzzy wasn't fuzzy was he?";
//Now let's include our functions page that will provide a function.
include 'functions.php';
//Now to use the function to create a new string
$string1 = MyFirstFunction($string);
//Now let's print the new string, then the old string
echo $string1;
echo '

';
echo $string;
?>

We will save this code and open a new editor page. This code will not run without us creating a functions page, so now we will do that.

<?php
//Define Function
function MyFirstFunction($var) {
//Let's tell the function what to do
str_replace(' ','+',$var);
str_replace('Wuzzy','was he',$var);
}
?>

Once we save this and execute home.php, in your browser you should see:

Fuzzy+was he+was+a+bear,+Fuzzy+was he+had+no+hair,+now+Fuzzy+was he+wasn’t+fuzzy+was+he?

Fuzzy Wuzzy was a bear, Fuzzy Wuzzy had no hair, now Fuzzy Wuzzy wasn’t fuzzy was he?

We can define a multitude of functions by simply defining them then putting them into use. It will save a lot of time on the coding end.