SEARCH
Newsletter
Subscribe to get design
tips, latest trends, free
stuff and more.
It doesn't look like an e-mail address

hosting

  Web Programming PHP Go to the next level in PHP

Go to the next level in PHP

Will PHP Apr 04, 2007

PHP FunctionsSo 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) {

nstead 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
?>

That's a very straight forward one. If you don't get this, just leave a comment and ask me about it, then I'll explain to you in further detail.

Happy coding!

   
subscribe to newsletter