Newbie Mistake

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Newbie Mistake

Post by JakeJ »

This isn't a question. I'm just posting a lesson learned by a newbie.

When using a custom function, always try to use 'return' instead of 'echo' for the result.

I wrote a function:

Code: Select all

function ffdate($months) {
    #$months = $months +1;
    echo date('F, Y ', strtotime("+ {$months} months"));
}
The first time I called this function inside of a table cell, no problem. But then I also created an IF statement to set a variable to $ffdate(months) and got an unexpected result which turned out to be the function echoing the results outside of the table also. It baffled me for a while, but then I finally realized my error.

So, unless you have a really good reason for using echo instead of return in a function, use return.
Post Reply