My PHP journey part 4.

Last time, we took on loops, today we’re taking on functions!

Functions are pieces of code which you run more than once, the perform tasks which may have to rely on more than once in what ever it is you’re running.

There are many php functions which you can find here, but you can build your own.

A function looks like this.

function myfunction (){

//something you want to run goes here
echo ‘This is myfunction’;


1. Define your function, so you know what it is, “function, myfunction”

2. Put in notes to remind you of what it’s doing

Paramaters and functions

function greet($name) {
echo “hello, $name”;

The $name bit, will only work within the function, inside the curly brackets.

Within the function you can write variables into it, but they are only local variables.

You can also apply some of that if, else decision makers into a function.

For example

function greet($name, $greeting=””) {
if ($greeting != . ‘, ‘ . $name;
else {
echo ‘hi,’ . $name;

greet(‘joe’,’way to go’);


Flow control basics

Now, we know why functions are useful, because they are a piece of code that we can run over and over within a php file.

Echoing things to the screen is great – but we want to start doing more sophisticated things like connecting to a database or something.

At somepoint we’ll need to send data out of a function.

Back to the code that called it.

How can we get stuff out of a function?

We use the keyword, return followed by the value we want to get out of the function.

It looks like this:

function returnThis() {
return “Here’s something”;


(Now, if you were to run this code, you would get nothing.)

There are a few ways in which you can can grab a value of a function, you can assign it to a variable or you can send it to another function that can process output.

A good example to use is trim($mystring)


$mystring = ” abc “; //Basic variable

Nothing will appear here but if we…

$mystring = ” abc “;
$newvariable = trim($mystring);
echo $newvariable;

Boom, the we can now see the function working.

We don’t always have to create a new variable to show a function.

We can just write something else.

for example:

function mulitply($a, $b) {
//$multiplied = $a * $b;
//echo $multiplied
echo $a *$b;

You’ll lose alot of performance points if you make to many variables.

Now, there’s a whole load we can do with functions – but to be totally honest, I feel at this point it’s going to take practice and a whole lot of coding to grasp it… At this point, I want to start building things – but where do I begin, do other coders learning the basics feel this urge, but don’t know where to start?

Let’s hope so!

Leave a Reply

Your email address will not be published. Required fields are marked *