20 Ways to Save Kittens and Learn PHP
basix

20 Ways to Save Kittens and Learn PHP

Tutorial Details
  • Program: PHP
  • Difficulty: Beginner
  • Estimated Completion Time: 1 hour

Twice a month, we revisit some of our readers’ favorite posts from through out the history of Nettuts+. This tutorial was first published in January, 2011.

There’s an old adage – dating back to the 1700s – which, in English, says: “A kitten dies each time a PHP programmer doesn’t follow best practices.” Okay, not really; but just go with it!

Getting started in PHP can be a daunting experience. With that in mind, these 20 tips will teach you how to follow best practices, and save lives…kitty lives.


0. Program as Often as You Possibly Can

Programming often and with purpose will make the lessons you learn stick.

Did you study a foreign language in school? Studied all the parts of speech, learned the verbs and how to conjugate them, followed along as your teacher said common phrases?

How much of that language do you still speak?

If you’re answer is, “none,” I’m willing to bet it’s due to the fact that you never actually used the language — you only studied it. But if you can still hold up a conversation, it’s likely because you actually spent some time speaking that language outside of the learning environment. Perhaps you spent a year abroad, or worked a job where a second language was necessary?

Whatever the reason, you retained it because you used it in real-life situations and put it into a personal context that is much easier to recall later.

PHP is a foreign language, just like Spanish or French. In order to become comfortable with it, you need to use it outside of the classroom setting. Tutorials and sample projects are great for teaching the fundamentals, but unless you’re applying those concepts to your own projects, it will be much more difficult to apply those fundamentals in context and burn them into your memory.

So, don’t worry that you “don’t know enough” to build a project. When you choose your project, you have a valid reason to research and implement a concept. Programming often and with purpose will make the lessons you learn stick.


1. Get Familiar with the PHP Manual

Every list of tips for beginners has this tip, and for good reason.

Learning to navigate the PHP documentation is the single most useful thing you can do for yourself as a programmer.

If you look in my browser history at the sites I most often visit, the PHP manual will be right at the top. I don’t suspect that will change for as long as PHP remains my programming language of choice.

At first, the manual does look rather daunting — it doesn’t seem to be particularly easy to browse, and the navigation can be a bit awkward at times. However, you’ll get the hang of it quickly.

Perhaps the best thing to know about the PHP manual is that most functions can be looked up using the pattern http://php.net/function-name in your address bar. For example, to look up the strpos() function, use http://php.net/strpos, and for array_key_exists(), use http://php.net/array-key-exists. (NOTE: pay attention to the omission of parentheses and the substitution of hyphens (-) for the underscore (_) in the address.)

1a. Read the Comments!

It's easy to overlook the comments, but do yourself a favor and have a look through them. If you're getting an unexpected result from a function, chances are someone has spotted it and explained it in the comments.

You can also pick up a plethora of great tips and ideas from the developer community by reading through comments.


2. Take Advantage of the Huge Online PHP Community

In addition to the PHP manual, there are wonderful developer communities all over the internet. Some of my personal favorites include StackOverflow.com and the W3Schools.com forum.

Additionally, Twitter is a surprisingly excellent place to post PHP questions. If you tag a tweet with #PHP, it's likely someone in the community will spot it and lend a hand.

A Note About Twitter: Of course, anything that's useful will inevitably be overrun with spammers and those sorry individuals who deeply misunderstood the purpose of social media. If you're going to use Twitter as a support network, you'll probably want to routinely block or hide the accounts which spew job postings or retweet everything that mentions PHP.

Just remember: as you get better, please try to pay it forward. The development community needs everyone to pitch in, and it won't be long before you'll have the ability to answer questions for other beginners. Don't turn a deaf ear.


3. Don't Put Off Best Practices for Later

As you're learning, you're going to hear a lot about "best practices" in programming; stuff like prepared statements and PEAR coding standards.

Do not put off learning this stuff because it seems hard.

If something is a best practice, it's not because we (meaning other PHP developers) got together and said, "How can we make life harder for the noobs?"

Best practices exist to keep your scripts secure, fast, and manageable. Learn them as early as you can. In fact, don't even bother learning the wrong way.

It takes just about the exact same amount of learning to figure out mysql_query() as it does to learn PDO or MySQLi. So if you start with your choice of the latter two, you're starting with a strong foundation in database interaction and, really, you've put in less overall effort.

Be sure to browse Nettuts+ for a variety of tutorials on PHP best practices, including prepared statement usage.


4. Don't Put Off Best Practices for Later!

I just wanted to make sure you saw this.

Seriously, folks. Don't take shortcuts. Every time you violate best practices because the right way seems "too hard," BP dips a kitten in crude oil.

So if you won't do it for yourself, your projects, your peers, or the advancement of the community at large, at least consider the kittens.


5. Make Code Self-Documenting

If you need to squeeze characters off your variable names to shave .2ms off your script’s execution time, there’s likely a whole different problem going on.

It's tempting, early on, to be "clever" with your variable and function names. Maybe you read an article about performance, or saw a code snippet that accomplished a ton of work in two lines of code. Maybe you want to create your own "signature style" of coding. Maybe you just heard that I hate it and you wanted to piss me off.

Whatever your temptation, resist it at all costs.

Consider the following snippet of code:

<?php

 $a = b('jason.lengstorf@copterlabs.com');

 $c = explode('@', $a);

 $d = $c[1];

 echo 'The email address ', $a, ' belongs to the domain ', $d, '.';

 function b($e) { return htmlentities($e, ENT_QUOTES); }

?>

Does that make any sense to you?

Of course, you can figure out what it does, but why force anyone trying to work in your code to spend the extra 1-5 minutes scratching his head, trying to remember what $c is storing.

So let's take that code and make it self-documenting:

<?php

 $email = sanitize_string('jason.lengstorf@copterlabs.com');

 $email_pieces = explode('@', $email);

 $domain = $email_pieces[1];

 echo 'The email address ', $email, ' belongs to the domain ', $domain, '.';

 function sanitize_string($string) { return htmlentities($string, ENT_QUOTES); }

?>

There. Much better. Now, just by glancing at the code, you can get the general idea of what's going on. No head-scratching, no muttered curses, and most importantly, no real difference.

Sure, you save a few bytes with short variable names. But, honestly, if you need to squeeze characters off your variable names to shave .2ms off your script's execution time, there's likely a whole different problem going on.


6. Add a Comment to Anything You Had to Think About

Comments are the sign of a competent programmer.

Comments are not the sign of a novice. In fact, as I see more and more code that's not mine, I'm starting to think that comments are the sign of a competent programmer, as they seem to be the only ones doing it.

If your code is self-documenting, you won't require too many comments. However, no matter how clear your variable and function names are, you'll always have spots where the action taken simply isn't that obvious.

When that happens, slap a comment in there. "Future You" will give "Present You" a high five when the time comes to update the script.

As a rule of thumb, if you had to stop and think for a few seconds about what needed to happen to make the script work properly, it's probably a good spot for a quick note.

Consider the following:

 
$pieces = explode('.', $image_name); 
$extension = array_pop($pieces);

What does that do? Did you have to stop and think about it? Do you still not know for sure what's stored in $extension?

Look at that snippet again, but with one quick comment:

 
// Get the extension off the image filename
$pieces = explode('.', $image_name); $extension = array_pop($pieces);

Now, even if you don't know how or why that code works, you at least know that $extension refers specifically to an image extension. If that saves "Future You" or another developer five seconds of processing the script's intent, it was well worth your ten seconds of effort to add the comment in the first place.

As with most things, moderation is key. Too few comments and you risk leaving the next developer (or Future You) puzzled by a code snippet, which can even lead to accidental breaking of code because the solution, without explanation, might look silly or superfluous. Too many and it becomes too difficult to scan through your code, which is equally frustrating.

Moderation is key.


7. Learn Docblock and Use It

If I could be sure every developer in the world would do one thing with absolute consistency, I think it would be the use of the Docblock commenting standard.

I have a few reasons for my strong support of Docblock:

  1. It requires one to think about the what and why for each file, function, method, and so on.
  2. It gives a clear description of the expected types for parameters and return values in functions/methods
  3. It provides a quick description of what the code does
  4. When coupled with one of the many IDEs that support Docblock, it creates code hinting (which allows you to see a description and expected parameters/return values for the method or function you're using)

This tip does border on the upper level of beginner, but I group this under "best practices to be learned as quickly as possible." Feel free to skip it, but before you do, think about the kittens.

Docblock shows its versatility best when used to document a class:

/** 
 * A simple class to get the sum or difference of $_foo and a value 
 * 
 * @author Jason Lengstorf <jason.lengstorf@copterlabs.com> 
 * @copyright 2011 Copter Labs 
 * @license http://www.opensource.org/licenses/mit-license.html 
*/ 

class CopterLabs_Test 
{

 /** 
  * The value to use in addition and subtraction 
  * @var int 
 */ 
 private $_foo = 0;

 /** 
  * Adds a value to $_foo and returns the sum * 
  * @param int $add_me The value to add to $_foo 
  * @return int The sum of $_foo and $add_me 
*/ 
public function add_to_foo( $add_me=0 ) 
{ 
  return $this->_foo += $add_me; 
}

 /** 
  * Subtracts a value from $_foo and returns the difference 
  * @param int $subtract_me The value to subtract from $_foo 
  * @return int The difference of $_foo and $subtract_me 
*/ 
public function subtract_from_foo( $subtract_me=0 ) 
{ 
  return $this->_foo -= $subtract_me; 
}

}

At first it might look overwhelming, but the benefits are very much worth taking the time to familiarize yourself with the syntax.

The above Docblock, when used in Netbeans, will generate the following code hint:

Code hinting in Netbeans

8. Don't Be Too Hardcore to Use an IDE

If you don't already know the type, you will soon: the developers who think real programmers don't use IDEs.

Now, look: if you want to impress people, learn to juggle. Refusing to use anything but Emacs in the command line to write scripts will not get you chicks or grant you instant hacker status; it will, however, hang a sign on your forehead warning your coworkers that you are, in fact, That Guy.

Don't be That Guy.

There is nothing wrong with using software to give you on-the-fly syntax highlighting, error-checking, and code hints.

How in-depth your IDE goes is entirely up to you. Personally, I really like Netbeans. I've heard tons of praise for Coda for Mac (though it's not really an IDE), and I previously used Eclipse before moving to Netbeans.

Whatever IDE you choose, you'll see your coding speed increase and your facepalm-worthy bugs decrease. Further, as you expand your code library, you'll have code hinting for all of your custom software. (Because you're using Docblock, right? Right?!)

Don't think IDEs are uncool -- no matter what "That Guy" tries to tell you.


9. Group Common Code Into Functions

If you see an action repeated, it's time to strongly consider moving that code into a function.

When you first start programming, it's easy to start at the top of the page and work down, adding each piece of code right where it's needed.

However, when you code this way, you'll begin to notice that certain pieces of code are appearing over and over again. This is a minefield when it comes to maintenance and upgrades, because you have to hunt through each file for every occurrence of that action to change its functionality.

If you see an action repeated, even if it's only twice, it's time to strongly consider moving that code into a function.

Consider the following for example:

$unclean1 = '<a href="javascript:alert(\'Holy Crap!\');">Click Me!</a>';

$detagged1 = strip_tags($unclean1); 
$deslashed1 = stripslashes($detagged1); 
$clean1 = htmlentities($deslashed1, ENT_QUOTES, 'UTF-8');

$unclean2 = "Let's call Björn!";

$detagged2 = strip_tags($unclean2); 
$deslashed2 = stripslashes($detagged2); 
$clean2 = htmlentities($deslashed2, ENT_QUOTES, 'UTF-8');

echo $clean1, "<br />", $clean2;

As you can see, both of those strings required a few steps before they could be considered safe to use. However, you'll also notice that those same steps could be considered necessary for every bit of information that is passed to the script.

This is an instance where using a function instead is far more desirable:

$unclean1 = '<a href="javascript:alert(\'Holy Crap!\');">Click Me!</a>'; $unclean2 = "Let's call Björn!";

$clean1 = sanitize_input($unclean1); 
$clean2 = sanitize_input($unclean2);

echo $clean1, "<br />", $clean2;

function sanitize_input( $input ) 
{ 
  $detagged = strip_tags($input); 
  $deslashed = stripslashes($detagged); 
  return htmlentities($deslashed, ENT_QUOTES, 'UTF-8'); 
}

By wrapping the common code in a function, it's a bit easier to see what's going on, and it's much easier to edit the steps you want to take when sanitizing your input.


10. Group Related Functions Into Classes

Getting a handle on OOP is another one of those things that I file under "best practices to learn as quickly as possible."

If you have a handful of functions that all deal with database actions, you can save yourself a lot of time and effort by grouping them into classes.

Learning object-oriented programming is definitely outside the scope of this list, but I felt it was definitely worth mentioning in this beginners' list.


11. Use Constants, Not Globals

PHP allows you to define your own constants with the function define().

When I first started programming on larger projects, I found myself using global variables more often than seemed necessary or reasonable. Admitting you have a problem is the first step.

I was storing things like application-wide data (such as the site's name or the maximum image width) and database credentials in variables, and I found myself required to use the $GLOBALS superglobal to access this information.

Then I realized PHP allows you to define your own constants with the function define().

A constant is a great way to store information like the aforementioned app-wide data and database info. An additional bonus is that it can't be modified, so you can't accidentally overwrite your database password somewhere later in the script.

As a matter of best practices, the use of globals is generally discouraged to begin with, so the use of constants is preferred anyways. Review the following code for an example and see for yourself:

<?php

define('FOO', 'constant value');

$bar = 'global value';

echo baz();

function baz() 
{ 
   $constant = ' Constant: ' . FOO; 
   $global = 'Global: ' . $GLOBALS['bar'];

   return $constant . "<br />\n" . $global; 
}

?>

12. Don't Be Afraid to Use Includes

Often, as you're building larger products, it will make a lot of sense to break it apart into smaller chunks, or include files.

A generally accepted way to look at includes is to put any bit of code that will be used in multiple scripts into an include file (such as your database connection details, the header and footer data that is common across the whole site, utility functions like your input sanitization actions, etc.) so it can be pulled in by the file that needs it, rather than being copy-pasted.

For example, on a site with multiple pages, a standard template may emerge that looks something like this:

<?php

// Application-wide data and database connection 
require_once 'constants.inc.php'; 
require_once 'database.inc.php';

// Utility functions 
require_once 'utilities.inc.php';

// Header markup 
require_once 'header.inc.php';

/* * Page-specific processing goes here */

// Footer markup 
require_once 'footer.inc.php';

?>

13. Don't Obsess Over Performance

This is a point of near-paralysis for some developers, and it's really too bad; there is a blurry line between writing efficient code and wasting time trying to squeeze an extra 5ms out of a script's execution.

Definitely read a few performance articles and learn some of the major pitfalls that can drag your scripts to a slow crawl, but don't waste extra time refactoring your code to change double quotes to single quotes because you found out it was a tiny fraction faster.

Use your head, avoid the big problems, and keep your ears open, in case a tip you've never heard comes along to speed up your code, but don't make it a race.

No one can tell the difference between a 25ms page load and a 40ms page load. Make sure it's not 700ms and move on to more important things.


14. Avoid Marrying HTML to Your Scripts

This can be tricky, but do your best to avoid tangling up your HTML markup in your PHP. It's nearly impossible to get away from it completely, but try to make sure that you don't include any non-essential HTML markup in your code.

Consider the following:

echo '<div class="example-div"><p>This is some test content.</p></div>';

Was it necessary for that code to wrap the paragraph tag in a div? Could it have been modified to only include the paragraph tag that holds the text? Have a look at an alternative solution:

<div class="example-div"> 
   <?php echo '<p>This is some test content.</p>'; ?>
</div>

Note: This example is grossly oversimplified. Generating HTML with PHP is usually more of an issue when dealing with a complex function or method that organizes a dataset. The point I'm trying to make is that it can sometimes be tempting to include more markup than is necessary in the output.

In most cases you can keep the HTML outside the PHP, which makes things easier to read and, usually, easier to work with as well.


15. Try to Use at Least One Unfamiliar Concept in Every Project

Push yourself outside your comfort zone.

You're never going to learn if you keep doing the same old thing. Try out a concept that you're not quite comfortable with on every project you possibly can.

Don't be over-ambitious, but definitely push yourself outside your comfort zone. It gives you a challenge, saves you from getting bored doing the same old thing over and over again, and forces you to progress as a developer.

Look at the project, find all the bits that you know well (or at least well enough), and then pick an area you'd like to understand. Sign up for it. Then do it.


16. Don't Be Too Proud to Change

You will be wrong. Frequently. But that's not a bad thing.

As you improve, you'll find newer, better solutions to problems that you've faced in the past. Don't feel stupid; you're learning.

But it's extremely important that you don't become attached to the code you write. Don't think your way is better just because it's your way. If you happen across a great solution that makes yours look like a Band-Aid on a bullet wound, use it! Pay attention to what's different and what you did that could have been better. File that away under, "Things I've Learned."

Never allow yourself to believe that an inelegant solution is acceptable because it's yours. That's hubris (which, if you're not aware, doesn't generally result in happy fun times).


17. Validate

If you're a web programmer, start becoming familiar with input validation as soon as possible.

Keep in mind: validation is quite different from sanitization.

Input validation is the practice of making sure data matches the format you've requested, like checking an email field for a valid email address or ensuring that a submitted username is 8-20 alphanumeric characters.

It can be tedious and a pain in the ass, but making sure that only valid data makes it through your processing scripts will enhance the user experience and avoid a lot of bugs in the scripts that have to use the data later on.


18. Whitelists Instead of Blacklists

If you're not on top of your blacklist, vulnerabilities appear.

In plenty of situations, you'll want to block or get rid of certain tags, words, email addresses, or other various bits of data.

A common solution is to use a blacklist: a collection of the tags, terms, etc. that aren't allowed.

This poses a problem, however; you have to be more clever than the person trying to do something naughty. For instance, in the case of disabling JavaScript in posts, you might blacklist the onclick attribute, as well as most of the event attributes, but what if you forget one? What if a new one is added to the spec sometime in the future?

If you're not on top of your blacklist, vulnerabilities appear.

However, to save headache later, use a whitelist whenever possible. A whitelist is the opposite of a blacklist: a collection of allowed tags, terms, etc.

For instance, in the strip_tags() function, you can provide a whitelist to specify which tags are allowed in strings:

strip_tags($string, '<em><strong><tt>');

Now your problem is most likely going to be that you can actually do less than you wanted, but that's far safer and usually less of an emergency to handle.

You can't get away with it in every situation, but saying what is allowed vs. what isn't will provide you with more confidence and control over your scripts.


19. Learn to Count Like a Computer

Are you looking for tip #20? Remember that in nearly all cases, counts in PHP start at 0, so this is actually the 20th tip. You'll find this to be the case in most languages; don't let this one trip you up!


Summary

If you're a beginner, the tips covered above will help you take great strides toward good habits and best practices. Don't get overwhelmed if all of this is news to you; take things one step at a time (see tip #15).

Tags: basix
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.54grad.de Karsten Vogt

    Going to safe a lot of kittens in the future ;-)

    This list feels more like zen_to_do -> change one habit a time!

  • Christophor S. Wilson

    Great Tut. thanks

  • http://airwolfe.com Alex

    Love the comment about IDEs. I know plenty of devs that use emacs or vim and I thought about switching for a while (played with both). Ultimately I realized, I’m faster with and IDE than anyone I’ve ever seen use either of those programs. Its about speed and productivity for me, I’ll use my extra time to play tennis or go hiking.

    Great article.

  • SalmanAbbas007

    Great Tips :)

  • SalmanAbbas007

    I’d like to add a tip :)
    Which is that DONT WASTE your time learning a php framework, code your own No-Framework Framework on your way ;)

    Pretty old but useful:-
    http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html

    • http://www.lastrose.com LastRose

      A framework can be an immense time saver, and I think that learning a php framework is a very good idea. That being said, You should always know the underlying language first before you learn a framework.

    • http://www.copterlabs.com/ Jason Lengstorf
      Author

      The argument for or against learning frameworks is tricky — on one hand, using a framework can get a novice programmer into the habit of using good practices quickly (CodeIgniter is a good example of this), but on the other hand it leaves you helpless if the framework doesn’t do what you need it to do.

      Personally, I don’t use a framework. But for some people, a framework is a much better choice.

      It’s on each of us, individually, to decide where to draw the line between doing it ourselves and leveraging the experience of the community that built these frameworks.

      I agree, though: make sure you understand the language you’re using before you start in with a framework.

    • http://djangoproject.com Jonas

      Beginners *should* code their own framework just to learn PHP properly, but once you have a lot of experience and getting products out the door matter, using a framework is usually the smart choice.

      (An ever smarter choice would be to use Python + Django, but that’s a different story :) )

    • http://heathshowalter.com Heath Showalter

      You must charge by the hour like me :D

  • http://www.wordimpressed.com Devin Walker

    Wow this is one of the greatest lists for PHP beginners I’ve read yet!

  • http://equiet.sk Equiet

    I really recommend learning a PHP framework. Most of them *require* all of these best practices. Don’t try to avoid them because of the learning curve – it’s worth it. Even learning a framework you won’t be using helps you better understand useful things like OOP or MVC.

  • Shaun C.

    Nice tip list! Especially love the last one – had to scroll back and see if you actually started at zero or not. ;D

  • http://www.luke-king.com Luke

    Great tips. I really like the one about try something new in every project. That is something I have aspired to do since I very first started making websites. Very tricky on the counting, I didn’t even notice ;) hah we are supposed to have attention to detail.

  • http://danaemc.com Danae

    Hehe, knew I would like this article as soon as I saw it start with “0″.

    One of the problems I find I’m having is that I’m way too vanilla. I love coding in Notepad++; the colours are enough for me to spot mistakes. I may look into NetBeans…

    I’ve recently got into CodeIgniter, which is brilliant, and has increased the amount of work I can do in a certain timeframe greatly, and helped me “get” MVC.

    Great read, thanks!

  • http://ksarwara.com Kanwaljit Singh

    I agree on your points, in fact, I am going to use OOPS, Docblocks, PDO etc in my next project, kind of for first time, God help me!!

  • Zoran

    Really nice roundup of tips for PHP developers, though when it comes to IDE, i have tried using NetBeans and PDT but my development was terribly slow (also they both worked slow on my laptop), sticking with Notepad++ armed with nice plugins makes my programming much faster and more productive, but i would still say it’s a personal choice, but for example while working with Magento which contains lots of PHP code, the only choice is IDE.
    Other things that i could add are:
    Once you are done with your PHP code, try to hack yourself, cause if you can do that, someone else could too.
    Learn and understand what PHP is capable of and what PHP cannot do, i have worked with developers with 1 or more years of experience who didn’t have full understanding of their tool (PHP in this case), cause with all the power that PHP posses comes great responsibility.

  • http://westsworld.dk Jimmi Westerberg

    Nice round up.

    Learning MVC might have been a very valid point as well though.

  • NoxArt

    #0 well … don’t take it literally ;) there’s a world outside

    #3, #4 DISAGREE – this akin to trying to get everything perfect right away, especially scourge of perfectioninst – start small! Don’t be overambitious

    #11 do NOT use constants, use variables/objects instead. With variables/objects holding the data you might pass a slightly different ones to a different parts of code, change it during the run etc. etc.

    #13 unfortunately there are many so called “perfomance articles” which just lists microoptimization nonsense like ” VS ‘ etc. The main attention is on the most used parts, especially frequently used loops with many iterations … more generally use the 80:20 (or 90:10) rule + profiling – find bottlenecks in the application and fix them.
    And yes – it’s important to pay attention to classes… definitely try to avoid things like N^4 scaling unless it’s rarely used and very short loop

    That being said – noone says you’re prohibited to use experience. When you increase a perfomance for some bottleneck and the similar situation appears elsewhere then you might consider using the same procedure as well – IF it’s suitable of course.

    More e.g. here http://programmers.stackexchange.com/questions/39515/at-what-point-should-you-start-to-think-about-performance

    #15 yes – and learn languages other than PHP! it greatly broaden one’s outlook
    #15, #16 – nice ones

  • http://mimrankhan.com Imran Khan

    man , this is awesome nice tutorial… after many days a good php one….

  • http:/7php.com kwasseem

    “Comments are the sign of a competent programmer.” ==> YES!!! It only makes sense!

    Yes Netbeans rocks! It beats the crap out of eclipse or the commercial Zend Studio.. after it offers all that candies FREELY! Use it people, use it! It has a very nice unit test and xdebug for step-debugging + a lot of very nice keyboard shortcuts..
    Sensible steps!
    Cheers!
    //Wasseem K.

  • http://www.arminder.co.uk Arminder Dahul

    Great set of tips. Can be applied to other programming languages too.

    Although some of the links in the article aren’t working, can you please correct them? Tip 3 and tip 11 are the two I tired to use but weren’t correct.

    • http://prop-14.com Randy

      Yeah, I noticed that too. Also, it seems there is content that got cut off?

      “So if you”….??

  • Develeper

    A Kitten dies every time somebody starts to type any PHP. PHP is bad in any category you can think of. The Code is ugly, inefficent, error prone, function differs based on the environment(not suitable for the Server-Side) and so on. Learn JavaScript. Or C#. Or even Java. Everything is just better then PHP. If none of those is a option, try Perl or something….

    • http://envexlabs.com Matt Vickers

      Anyone who is new can just skip the comment above :)

      That’s my greatest tip.

    • http://www.jeffrey-way.com Jeffrey Way

      Language wars have never solved anything…

      Not sure how recommending that a PHP developer learn JavaScript makes any sense — as they accomplish entirely different things.

    • http://www.ashmenon.com Ash Menon

      That would suggest that JavaScript is capable of accomplishing anything PHP can do. As far as I know, this is incorrect. And please do not trash an entire language like that. There are sites that use PHP to deal with millions of users and they do it beautifully. I’m guessing you’ve had some crappy experiences with it, but no need to piss on someone else’s rainbow.

      • znet

        I agree with “Develeper”, and I think he is referring to the language in general. It’s completely messed up and has no internal structure. They even added “goto” recently!

        The single biggest problem with PHP remains that it is incredibly easy to write horrible code and quite hard to write good, readable code.

        Plus, it makes it far too easy to mix markup and code. VERY bad idea. Do you know why casts in C++ are that ugly (using static_cast)? SO YOU AVOID THEM! (Well, PHP casts everything around and will happily compare things no one would ever dream of comparing, resulting in a non-transitive == operator).

        My advice is: if you are tempted to try out PHP, be warned. And have a look at some other language, too, like Python. Or Ruby, if you prefer. I prefer Python.

    • http://tedlee.net Ted

      Hey “Developer”… When C# or Java reach the level of server penetration that PHP has, and can be deployed for the same costs as deploying on LAMP, we can talk.

      Perl is a dead language for web development. You’d be better off learning Latin, as you would probably get more use out of it. Java’s future is clouded, thanks to Oracle. Many of the shops I know that were pure Java are now looking as Ruby for their lifeboat. C# is a Microsoft creation. Next.

      And Javascript (client side) isn’t used for the same problems that PHP (server side) is, so you’re suggestion to learn Javascript to solve server side problems is ridiculous.

    • http://www.visual-blade.com Daquan Wright

      A good programmer can write good code in any language, even the shittiest ones.

      A bad programmer will write bad code in any language, even the best ones.

      Learning the faults of PHP will make you better, because it requires discipline to do so. Writing good code is a matter of state of mind, not simply syntax.

      If you’ve read JavaScript: The Good Parts, you know what I’m talking about. JS has many horribles features in the language, but by knowing the bad parts to avoid, you get an expressive and capable language.

      If it’s possible to write good code in JS (and it is), it’s possible to write good code in PHP. Not to mention JS has far more problems from the inside….

      JS can be used on the server, but for all realistic purposes, that’s not where JS excels. Comparing PHP to Ruby/Python is more sensible. Java is a tough language and is not beginner-friendly, unlike the three popular dynamic languages.

  • Ben

    your*

    • Ben

      If **you’re** answer is, “none,” I’m willing to bet it’s [...]

  • Techeese

    honestly, the Title caught my attention.

    Anyways, very great PHP tips and yes, save the kitties :(

  • Greg Tyler

    Sorry to do this but in section 3, “Don’t Put Off Best Practices for Later”, there’s a sentence that starts “So if you” and then doesn’t end. And now I’m hopelessly intrigued to know what it is I may do.

  • http://netcutter.org/ Kiril Vladimiroff

    About point 6: “Add a Comment to Anything You Had to Think About”.

    I’m not quite agreed with this. I don’t mean “f*ck the comments, I don’t need them”. As you say, by your own, the code should be self-documented.

    But if there is a need for adding comment line for every simple code block in each method…then there is something really wrong in your code. Could should speak for itself ;)

    • http://www.copterlabs.com/ Jason Lengstorf
      Author

      That’s actually exactly what I meant.

      Most of your code should be self-documenting, but there are always cases where a section isn’t immediately clear. THAT’s when comments should be used.

  • khaled

    Great tut thank you !

  • Bohdan Ganicky

    If you really learn how to use Vim, you are going to be much more efficient than in any IDE. Moreover, you can make your Vim “IDE-like” as well. Just google “Vim as PHP IDE”.

  • http://www.antonagestam.se/ Anton Agestam

    @8 Aptana Studio 2 (Aptana 3 is coming soon) is a really nice IDE for PHP

  • Nikush

    Awesome article. Thanks!

  • http://ethan.heroku.com Ethan

    You can save twenty puppies by using Ruby instead of PHP.

    • http://djangoproject.com Jonas

      However, Python + Django is the ultimate kitten saver :)

      Also, a recent poll on Hacker News showed that the most used serverside language with new startups is Python.

    • nuku

      And you can save forty little snakes by using Pythong instead of Ruby ;)

  • http://www.lastrose.com LastRose

    Great article!
    Good coding practices are essential, especially when you are working on a team. if you look at your code in 6 months and wonder what is going on, just try to imaging what someone looking at it for the first time will think.

    Don’t be afraid of the php manual. Even php programmers who have been programming for many years still refer to it. I know one guy who keeps a copy on a usb key so he can refer to it at any time. There are so many functions in php, that it is next to impossible to remember them all, especially if you don’t use all of them on a day to day basis (has anyone ever used every single php function?).

    Refactoring! Don’t be afraid to go over your code when you are finished and ask yourself how you can make it better. I wrote an application procedurally, then converted it to object oriented, and then did it with a framework. Each time the application got faster, cleaner, and smaller and easier to manage. On the other hand I know a company that never refactored anything, they just kept adding to old code and ended up with a huge mess, including a folder with so many files that it couldn’t be opened (they where writing sessions to a file, and never deleting them) and a database that had hundreds of unnecessary tables. It was so bad, that when they wanted to seriously update the application to add a few new features and update the styling, they decided to start completely fresh because they just couldn’t make it work with the mess they had. Just because your done with a project doesn’t mean you’re finished with it.

    Don’t Repeat yourself!!!!
    It was said, but needs to be said again.
    Even the example given the cleaner code still repeats itself. If you had 4 or more, you would have to do a bit of repeating. The function saves time, however there is a better way of doing it.
    Store all the values in an array, and run array_map() on the array.
    would look like this

    $unclean1 =array( ‘<a href=”javascript:alert(\’Holy Crap!\’);”>Click Me!</a>’, ‘Let’s call Björn!’,'some other value’,'another value here’,)
    array_map(“sanitize_input”,$unclean1);
    print_r($unclean1)
    function sanitize_input( $input )
    {
    $detagged = strip_tags($input);
    $deslashed = stripslashes($detagged);
    return htmlentities($deslashed, ENT_QUOTES, ‘UTF-8′);
    }

    if you have two functions that do similar work, see if you can combine them. For example, you have one function the squares, and returns, and another that cubes and returns, make them one function with the factor as another variable. That way, if you need to perform another similar function you won’t have to write another function.

    This doesn’t just apply to code, If you need to repeat information (think address, email, phone number) make it a constant, or return it from a function, but don’t repeat it! Just think at what would happen if you where to change email addresses. How many places would you have to change it? Would you remember all of them. Would you remember all of them 6 months from now? would someone else be able to find all the places you used them?

    One final note. Pick a naming convention and stick to it!
    If you call your update functions update_field, keep that standard, don’t change it to edit_field or updateField for each new function. By keeping to a standard naming convention, it will be easier for you to remember as you go along, and it might also help with preventing repetition.

    • http://guibarbosa.com Guilherme Barbosa

      An article into another article. Cool. I’m just not going to read this.

  • Ibrahim Azhar Armar

    Very nice and informative tut. I really loved the way the author used to explain certain things, i recalled the day when i wrote my first php script file. It took almost 800 lines for me to submit a single form, i used sessions and cookies so heavily, seeing back the script again makes me laugh, and from then on i vowed i will work hard on improving my codes and since then i learned and began usin OOPS in my scrpt, and since then it has been a learning curve for me, the web is so vast. Every morning when i sit infront of my computer i feel i have still learnt nothing and there are so lot to catchup, the world is developing very fast and so is the technology.

    • martin

      @Ibrahim, 100% agree! Web development itself is such a complex topic, yet I’m still hungry for more. If I see what some developers are able to create I feel I have a looong:o) way to go to become one of them, but I’m trying to focus on what I already know and build those skills step by step.
      Thanks Jason for sharing your experience here. Great Article.

  • http://www.techgangster.com Jeff Hendricks

    Nice Tut!! For a newbie, a great lead…keep it up.

  • Ikon

    When I was a begginer in PHP I loved to use an IDE. Now after almost a decade I got a great tip from one of my bosses. Try and use something like notepad++ and code with that. Your brain will get winded up as it needs to memorize more and more details on the project. First it sound a bit crazy in the world of thousands of files projects, but after only one month I started to feel better, more productive and having more knowledge on the project internals I am working on.

    All in all, for begginners an IDE is almost a must, but later they can try Vim or other non-ide editors as well. :)

  • http://matt@mattcarpenter.com Matt

    Thanks so much. Three things in particular really helped me here:

    0 – I no longer feel like a dweeb for using NetBeans.

    1 – As this is a tutorial for those who are new at PHP, I don’t feel too embarrassed to ask a basic question: On Item 14 (‘Avoid Marrying HTML…’), in your improved example, could you have also wrapped the tags outside the PHP and thus gone further with the concept of keeping markup outside of code?

    2 – I’ll repeat your hint about DRY practices (Item 9) over and over. (Sorry – I have a juvenile sense of humor.)

    Thanks again!

    • http://www.copterlabs.com/ Jason Lengstorf
      Author

      Regarding your question on markup in output, you’re absolutely right. The <p> tags could have been moved outside.

      That example was really, really oversimplified. Any example that really illustrated the point would have been too big to be practical in this context.

      The concept stands, though. As much markup as can be kept outside the PHP should be.

  • http://dascritch.net Da Scritch

    NEVER go to W3Schools ! just ban this site from your bookmarks, and you will win enormous time

    http://w3fools.com/ for more infos about why w3schools is completely bogus, even in PHP in its forums.

  • kalusn

    I’d like to comment on how you describe your use of IDE’s, without taking on the role as “the other guy”.

    First, let me emphasize the importance of good naming conventions. In many cases good naming conventions can replace commenting, for much more clean and concise coding. If your naming is good, your code most often is too.

    The main feature of using IDE’s is auto-suggestion. I just finished a course on OOP in my studies of computer science and I must admit, that Eclipse was a big help to me in learning java.

    But that’s my point: IDE’s can be good if you’re getting to know a new library. If you use auto-suggestion to keep track of your own classes and methods, it reveals a flaw in your naming convention. Good naming means that if you know what a function is supposed to do, you can more or less guess the name of it. Auto-suggestion can be a bad habit that ultimately leads to bad code, because if you use it, you aren’t forced to name your methods sensibly. And that’s why IDE’s is not always the right choice.

    • http://www.copterlabs.com/ Jason Lengstorf
      Author

      I agree that they shouldn’t be used as a crutch.

      However, expected parameters (and their types) and the expected type of the return are tough to include in the name of a method, and if you’re writing large, complex applications, it’s unreasonable to expect to memorize all of that.

      As with everything, it’s not a perfect solution. Irresponsible use of any tool will result in bad code.

  • http://www.imstillreallybored.com Josh Bedo

    loved the article a lot of information i also like the section about IDEs i know a few people that will strictly only use notepad ++. I know i tend to use notepad ++ a lot but its only because the other IDE i use is dreamweaver and its insanely slow when you have a lot of files open and are connected to a web-server. I tried Netbeans before i dont know why i stopped using it.

  • Patrick

    Seriously? Last point is brilliant.

    But most others too ;)

  • Ionut

    Great article. I`ll deffinetly keep them in mind. :)

  • ChrisH

    On the PHP manual thing, add a keyword search in Firefox or Chrome (maybe safari too?) so you can just type something like ‘php sqllite open’ in your address bar.

  • http://andrewburgess.ca Andrew Burgess

    Great list of tips; what’s great about this list is that most of these tips work for mastering any programming languages, not just PHP.

  • http://johanneslang.blogg.se/ Johannes

    LOVE it. More of these please! :)

  • notta

    Wow, great tips. Number 15 is so true. Great post.

  • Erik

    Your example of self commenting code could be changed to be more readable, imo:

    list($name,$domain) = explode(‘@’, “erik@example.com”);
    echo “$name at $domain”;

    Much less busy work then assigning the explode to an array, then index 1 to a var $domain.

  • Lare

    Whats wrong on using http://php.net/array_key_exists ?

  • http://nilambar.com.np Nilambar Sharma

    Nice tips. I did not notice u started from zero. :D

  • http://www.hambrook.co.nz Rick

    Tip #19 never catches me out, but gets a lot of people and is a BRILLIANT end to your article, which was also well written. I would’ve written the image file extension code differently, but that wasn’t the point of the article. Great for beginners and a nice refresher, thanks.

    • http://www.hambrook.co.nz Rick

      Oh…

      • http://www.hambrook.co.nz Rick

        Maybe without the php tags…

        function($filename) {
        {
        return pathinfo($filename, PATHINFO_EXTENSION);
        }

  • http://www.ashmenon.com Ash Menon

    You had me at the zero-based count. Awesome list of things, and I’ve learnt a lot from this. Thank you!

  • http://www.helloeverything.co.uk David the Web Designer

    Nice tips here, i use Coda most of the time but recently i have been using textmate, id recommend it!

    • Tobiás Előd-Zoltán

      Great windows alternative to textmate is E – Text Editor. Small but has the same bundles capability.

      Also #TIP: Write -> Test -> Write -> Test. Never bite of more than you can chew and as much in the beginning as later on it’s better to write bit by bit and test often than end up with a massive cluster-**** and having to search for half an hour for a missing parenthesis in 60 lines of code.

  • Marcus

    People in the comments seem to continue underestimating “Commenting Code”. It’s very important!
    Problem is that most developer feel that their code speaks for itself, thinking “Well this is easy! Ofcourse I’m using this_function() to improve the safety and avoid Bug #412523″.

    1 year later you quit your job and someone else needs to edit your code. They enter it and because of your lack of comments, it takes 10 times longer for him to add additional functions and edit some other parts.

    COMMENT!

  • http://www.movieviews.be Dennis

    Thank you for this nice article.

    Bookmarked !

  • http://tedlee.net Ted

    Not sure about your comment that Coda isn’t really an IDE. IDE stands for integrated development environment, and that’s exactly what Coda is: an integrated set of tools used in the task of developing.

    Also, for your 19th tip to really be the 20th, your tips would have started at 0. But since you started at 1, you only had 19 tips, not 20.

    Quibbles aside, nice collection of tips that I would absolutely recommend anyone learn, live and love.

    • Jason

      Well, he did start at 0. =)

      0. Program as Often as You Possibly Can