I am a php beginner coder.

I always find myself in a mess when I try to alter or add something to my scripts. Because they are not well organized.

So, I want to learn how to organize my code, so it becomes easy later on to change it.

Also, there is a lot of code snippets that I use frequently in all of my scripts. Like the database codes. Is there is a way to arrange those snippets?

  • 2
    Might be better suited as a community wiki, as I doubt there is one "correct" answer.
    – Brad F Jacobs
    Apr 21, 2011 at 16:41
  • 1
    Have a look at the MVC pattern. It's pretty useful. Voting to move this to programmers
    – JohnP
    Apr 21, 2011 at 16:42
  • Clean and well-organized PHP code is not so different from other languages. The same tensions apply and the language provides similar features that can be used to resolve them. Apr 21, 2011 at 18:43
  • You can write clean and organized PHP code? :)
    – Jas
    May 10, 2011 at 11:08

3 Answers 3


Learn Object-Oriented Programming:





  • I would argue that OOP code isn't any cleaner that procedural code, per say. I've seen OOP code that is messier and less organized than comparable procedural code.
    – Craige
    Apr 21, 2011 at 17:06
  • 1
    OOP is way of organizing, not a panacea. That's why I said learn and not do. :) Apr 21, 2011 at 17:08

Using a convention-over-configuration framework (1)(2)(etc) would help you organize your code to a decent extent. They can only do so much for you however, as in the end it is still up to you to do logical things.

The benefit of a convention-over-configuration framework is that it guides you in the right direction by making you do things by a standard convention unless you explicitly override(configure) it.


I think you need to learn OOP and a template system like Smarty.

Note : this will make you code well but slowly

Here are some guidelines that may also help:

  • Use comments in PHP// # /* */ not HTML.
  • Use good variable names to denote what you are using.
  • Cut the style as header , nav , right , left , center , footer , others.
  • Move styles codes a separate file and just link it.
  • Move PHP code to the top of the file and the forms and HTML to the bottom. You you can use PHP with HTML(when required). Ex: you can make your query and row check in the top of the page and merge the loop with HTML.
  • 2
    Mixing HTML with PHP in a single file is pretty much the definition of "unclean" code.
    – Craige
    Apr 21, 2011 at 17:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.