Log in

View Full Version : Functions...



alexjewell
08-26-2006, 09:21 PM
I'm using functions on a website I'm creating.
I'm curious if we can use if statements, etc in a function?
For example:



function my_function($yeah) {
if (...) {....}
elseif (...) {....}
else {....}
}


the periods obviously represent the content...

at any rate, is such a thing possible?
I have statements that repeat themselves, with just one part changing. so I figured if I could just call a function for it, I wouldn't have to keep rewriting the statements?

Thanks

blm126
08-26-2006, 09:23 PM
Yes. That is the whole point of functions.

mburt
08-26-2006, 09:50 PM
What is a function without statements?

Twey
08-26-2006, 09:59 PM
Well... one of them :)

A note on elseif: don't use it. It's directly equivalent to a plain old else if, but designed especially for stupid people and lazy typists. :) Using it is a bad habit, and it doesn't exist in most languages anyway. Its existance in PHP is another indicator of what PHP has sacrificed to become a rapid-development language.

mburt
08-26-2006, 10:04 PM
Wait a minute... I've used "if (...) {...}" many times over and not once, have I had to use an else if. What's "else if" for?

Twey
08-26-2006, 10:16 PM
It's to do with braces. When only one statement is conditional, the braces are not necessary; for example,
if($var) $var = false;
else $othervar = true;However, an if block is considered a single statement, so:
if($var1) {
dog();
cat();
} else if($var2) {
bird();
fish();
} else {
fox();
rabbit();
}is equivalent to:
if($var1) {
dog();
cat();
} else {
if($var2) {
bird();
fish();
} else {
fox();
rabbit();
}
}

mburt
08-26-2006, 10:20 PM
Ah, I see. I get it now :)

alexjewell
08-26-2006, 10:26 PM
Ok, thanks.

And from now on I'll use "else if"....
haha
:)