ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Creating and Working With Your Own Functions Using PHP, Part One

Updated on November 25, 2018

In part one of this tutorial, we will be making a basic contact form. Then I will show you how to make some basic functions of your own and how to use them.

Before we get started, PHP has well over 400 functions that you can use.

Below are some examples:

count()

preg_replace()

phpinfo()

And many more. So with that said, let's look at the advantages of creating your own custom functions. As you start to create larger projects and you are reusing large chunks of code over and over again which can become time consuming, this is where creating your own custom functions comes to the rescue and saves you a lot of coding time.

For example, what I mean is that I have this very large project and I have throughout the code an error message code snippet that pops up when an error happens like for say every time a field is not filled out in a form and I have many forms that use the same error message again and again. This is where a custom function comes in handy, see example below.

1. if((!$_POST[name]) || (!$_POST[message] || (!$_POST[email]))

{

echo ("A field was left blank please go back and try again.");

}


Now instead of typing "A field was left blank please go back and try again" over and over again, or you could just do the following.

2. function emptyfield()

{

echo ("A field was left blank please go back and try again.");

}


Then use the above function like so:

3. if((!$_POST[name']) || (!$_POST[message]) || (!$_POST[email]))

{

echo (".emptyfield();.");

} else {


Now I will explain what I have just done. First we declared our function. Then we gave our function a name. In this case I give the function the name emptyfield with two parenthesis (). The two parenthesis () must be at the end of your named function. Next I placed a brace right after that brace I place the code that I wanted to be called upon or executed. Then I close it with another brace, you must make sure you do this or it will not work. There you go, a very basic function ready to be used.


Now as you saw I did something different in the code sample in number 3 compared to number 1 where it says echo “.emptyfield();.”; what is happening here is that when a field is left empty it will execute the function by doing a function call re: emptyfied(); and it will echo out the message/ print it to your browser.


The function call can occur anywhere within the code, as long as it occurs after the function has been declared.


Before I go any further there are some rules that must be followed. Naming conventions must be adhered to.


Also you cannot name your function a name that is already predefined by PHP. For example count().


You cannot start a name of a function with a digit and you can only use letters, digits, and underscores.


Here are some samples of legal and illegal function names.
Legal Samples:
butterfly()
butter_fly()
butter_fly_5()
_butterfly()

Illegal Samples:
1butterfly()
butter/fly()
count() (This last one is not illegal only because the function already exists.)

Next I am going to show you some things you can do with functions.


In this next part we are going to make a contact form and use functions in various ways to display and process our form.


With all that said, let’s start off with a basic contact form.

So first let’s create to files one named form.php and one named form_process.php. Now before we continue let me just say that we are going to first create the standard way to do it then we are going to bring our own functions into the mix. Please do use these following examples on the internet as they are not very secure.


Now let’s create our first script form.php.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Basic Form</title>
   </head>
<body>
<form action='form_process.php' method='post'> 
<table cellspacing='0' cellpadding='4' border='0' width='60%'>
  <tr>
<td>Name:</td>
  <td><input type='text' name='name'></td>
  </tr>
  <tr>
    <td> Email:</td>
  <td> <input type='text' name='email'></td>
  </tr>
    <tr>
    <td>Message:</td>
  <td><textarea rows='5' name='message'></textarea> </td>
  </tr>
    <tr>
    <td></td>
  <td><input type='submit'value='Submit!' name='formprocess'></td>
  </tr>
  </table>
</form> 
</body>
</html>

There it is our basic form, now next we create the form_process.php. This is the file that will process our form when we hit the submit button.
form_process.php

<?php
// This checks to see if the submitt button was clicked
// If so then it retreves the information that was 
// inputed into the fields
if (isset($_POST["formprocess"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

// Here we check to make sure all the fields are filled in
if(empty($name) || empty($email) || empty($message))
{
// if one of the fields is empty then we tell them to 
// go back and fill in all fields
   echo ("You forgot to fill in a field! <a href='form.php'>Go back.</a>"); 
}
// All fields are filled in go to the next step
else {

// Here we echo out a message telling them email is sent
echo ("<p>Thank You, your message has been sent someone will be in touch with you shortly.</p>");

//Now here instead of sending an email, I just echo out the filled in fields
echo ("$name<br />");
echo ("$email<br />");
echo ("$message");
}
}
?>

As you can see it is very basic as it is just an example. Now I did not include the code to actually send an email as I was just trying to keep it simple as this tutorial was about creating and working with functions.

Now let’s step it up a knotch, first we are going to create a file named main.php and we are going to put the following code block into it.

main.php

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Main Page</title>
   </head>
<body>
<?php
if(!isset($_GET['p']))
    $_GET['p'] = null;

switch($_GET['p'])
{

case "":

break;

default:

break;
}

?>
</body>
</html>


Let me explain what we just did, we added our html of course. Now in between the PHP opening tag <?php we enter the following (if(!isset($_GET['p'])) $_GET['p'] = null;). The reason for this is when we load this page in our browser so this error doesn’t happen (Notice: Undefined index: page on line 11).

Now the reason is when we added the second chunk of code there was no variable assigned yet so it would cause the error to happen. So what we are doing is evaluating a true or false statement and because no page has been defined yet in our variable we tell it then it is null.

In the next chunk of code we used the switch and cases statement.

A switch and case statement is when you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to.

We are going to use our switch statement as a navigational system.

Ok now let’s put our main.php file to work, right where the default: case is in our switch code block add this line:

(Include “form.php”;) before the break;

it will look like this:

default:

include "form.php";

break;


Now call main.php up in your browser and you will see the form. Now next in our switch code block add the form_process.php here:

case "":

include “form_process.php”;

break;


Now where it says case””: do this case” formprocess”:. Now for this to work we have to make one more change in our form.php right here:

<form action='form_process.php' method='post'>


Change it to:

<form action=' main.php? p=formprocess ' method='post'>


When you have the changes done, try it out and as you can see it works.

Now with that out of the way let’s create some basic functions of our own. First let’s create a new file and call it myfunctions.php and let’s include it at the very top of our main.php file like so:

<?php

include "myfunctions.php";

?>

<!DOCTYPE html>

<html lang="en">

<head>

<title>Main Page</title>

</head>

<body>


Now in our myfunctions.php file we are going to create our first function, like so:

function form()
{
echo ("
<form action='main.php?p=formprocess' method='post'> 
<table cellspacing='0' cellpadding='4' border='0' width='60%'>
<tr>
<td>Name:</td>
<td><input type='text' name='name'></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='text' name='email'></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea rows='5' name='message'></textarea></td>
</tr>
<tr>
<td></td>
<td><input type='submit'value='Submit!' name='formprocess'></td>
</tr>
</table>
</form> 
");
}

So what have we done here? Well first we declared our function, function name of function at line 1, then we placed an open brace at line 2 and at line 25 we put a closing brace. In between the opening and closing braces is where we define our block of code and this is what we want our function to execute.

Next at line 3 we used echo() which is a means of outputting text to the web browser and we did this like so echo(“, then from line 4 to 23 we used the code block form our form.php file and the on line 24 we closed our echo() statement like so “);. What is happening is we are telling echo() to execute(print) the block of code between echo(“ and here “); to be printed to our out browser.

Then we closed our function with a closing brace { at line 25, now to make our function work go to main.php and to this code block

default:

include "form.php";

break;


in the switch statement and change it where it says include “form.php”; to form(); so you will end up with this:

default:

form();

break;


What we are doing with form(); is calling the function form() and telling it to execute the block within it, it’s just that simple.

Next we are going to make a small change in our switch statement right after our case"formprocess": , and change the include “form_process.php”; to form_process(); I think you know where we are headed with this. Now open your form_process.php file and copy the code block in between the opening and closing PHP tags.

Now open your myfunctions.php file and write our first function we created.

Start a new function like so:

function form_process()

{


}


Now paste the code block from your process_form.php in between the braces and save your work and give it a try. As you can see it works the same as it did when it was two separate files.

Now you only have two files to manage instead of three.

That is just one of the reasons why functions are so great it makes code updates or changes easy, because the change needs only to be implemented in a single place in the function definition and it makes our applications smaller as we needed less files.

Now you’re asking what’s next?

Well we are going to step it up one more notch. First we are going to make some changes to our main.php file and create a new case statement right above our case”formprocess”:

Like so:

case"ourform":

form();

break;


What we have done here is moved our default form(); to its own case statement and called it ourform.

This does not change anything to the form directly and it will no longer be called up under our default case. Now that we have that done, let’s now make a change to our default case like so:

default:

echo ("<a href='main.php?p=ourform'>Our Form</a>");

break;


As you can see what we are doing here is creating a link to our new case statement ourform and printing it out to our browser.

Save your changes and give it a try.

Now that was quite easy wasn’t it and you are still only using two files.

Now let’s go a little further and create a function and call it mylinks. Oh yes I think you know where we are going with this…


Ok first let’s open our myfunction.php file and right at the top of the file add this like so:

function mylinks()

{

echo ("<a href='main.php?p=ourform'>Our Form</a>");

}


And save your changes. Now open up main.php and at the default case change it like so:

default:

mylinks();

break;


Now save your changes and test it out. Look at that, you now have three of your own custom built functions and they work.


Well, that concludes part one of creating and working with your own functions using PHP.

I hope you found this tutorial helpful in your journey into PHP coding.

In part two, I will cover separating our presentation code from our process code and also show you how you can call/execute two functions at the same time and one function being in the other.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)