Hi, Guest ~ Login or Register

Functions

Functions

Listed In PHP and MySQL » Basics — Viewing Full Tutorial
So you've heard about functions, and what they can do.. and how leet they are. Now its your turn to write your own function. First of all let's recap what functions do, how you define them and how to call them.

What functions do
Ever had to do the same thing more than once? It compiles a load of code that you can put one or more variables through, and spits out the output without you having to go through the same process or copy and paste it.



And they're useful for..?
Repetitive scripts, big sites and so on. It's good to have a centralised functions file or even a class (which I'll come onto later) so you can call them anywhere.

How'd you define them?
We start off with writing this: function newFunction($var1, $var2) {Instead of newFunction you can write the function name. With $var1 and $var2, you can have one variable or any amount you want. You can also use any name for the variable; it's useful to give variables relavant names so you know what you're inputting. Your complete function would look something along the lines of this:<?php

function newFunction($var1, $var2) {
#your function code here..
return $var1;
return $var2;
}
?>
And so on.

Now we're going to make a script that does something quite trivial - checks if a variable is a number or not. If it's not a number, it will notify the user that it's not numerical, and if it is it will tell the user that it is. (Yes, I know there's a function that already does that for you, I'm only giving an example)

So let's write the function:<?php
function isNumber($number) { // names it
if(ctype_digit($number)) { // is it a number?
echo "This variable is a number!"; // yes it is!
}
else {
echo "This variable is not a number!"; // no, it's not
} // end function
?>


You can call this function simply:<?php
isNumber('hello world!');
isNumber(49);
?>


The first output will echo "This variable is not a number", whereas the second output will say the opposite.

There is no limit as to how many arguments you can introduce into a function.

Working Beta

  1. The Forums
    These are mostly functional. If you see any weird bugs, post a thread about it and an administrator will do something.
  2. Tutorial Writing
    You can now submit tutorials to the brand new management system.
  3. Tutorials Home
    View tutorials by categories and search for them here.
  4. Shoutbox
    See below. Registered users only!

Register

Newest User

Say hi to gazzamc! gazzamc joined on Saturday, 16th August.

Sponsor

Check out Next day fake id

Shoutbox