Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

PHP Development Part 2 – Functions

Wednesday, January 18th, 2012 by Servage

Hi again, please enjoy the second part of our PHP Development guide for beginners. This part is dedicated to functions.

Functions are small pieces of code, that perform a calculation, check or anything you want. The reason why these pieces of code are made available as functions, is so you can re-use the same functionality again and again, without reprogramming the same thing over and over. Consider a simple example: You want to display the following text for each user logged in to your website: “You are from England”, where England is a variable depending on the individual user. In that case, you could consider a function like this:

function write_country($country_name) {
	return 'You are from '.$country_name;
}

echo write_country('England');

You can use functions for various purposes. One of the most important concepts for functions is the return value. The return value makes it easy for you to continue your operation with the given result. The above example simply return the text string you want to display. It could also be something more advanced. Consider the following example:

function is_greater_than($number, $limit) {
	if ($number > $limit) {
		return true;
	}
	else {
		return false;
	}
}

$a = 10;
$b = 5;
if (is_creater_than($a, $b)) {
	$a.' is greater than '.$b;
}
else {
	$a.' is NOT greater than '.$b;
}

You can use functions in many ways. In general you should never program the same thing twice. So if you need to reuse some code somewhere, make a functions. In a chapter further down the road, I will discuss how you can bundle functions in so-called classes in object oriented programming. But for now, play with functions :-)

PHP Development Part 2 - Functions, 3.0 out of 5 based on 2 ratings
Categories: Guides & Tutorials

Keywords: ,

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.