Digital Web Magazine has a luculent article, Being a PHP Lumberjack, on how to use logging to track down PHP errors in your code when the results (output) you are getting is not what you intended. What Daryl L. L. Houston describes is standard procedure in the programming world and every computer science student learns early about instrumenting their code. This is a long article, but well worth reading if you are having any problems with your PHP code. The concepts covered are applicable to other programming languages. [Yes, librarians do write and modify code.]

Additional resources:
Wikepedia entry on debugging code: Debugging - Wikipedia, the free encyclopedia
Answers.com entry: debug