Functions
Listed In PHP and MySQL » Basics — Viewing Full TutorialWhat 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.
