You are on page 1of 55

PHP Tips 9 Article about PHP Tips

1. http://mashable.com/2010/10/21/php-tips-for-beginners/ 2. http://www.phpbuilder.com/columns/vaska20050722.php3 3. http://www.htmlgoodies.com/beyond/php/article.php/3907521/Top-10-PHP-Tips-forDevelopers.htm 4. http://net.tutsplus.com/tutorials/php/quick-tip-7-super-handy-php-functions-for-beginners/ 5. http://www.wmtips.com/php/tips-optimizing-php-code.htm 6. http://coding.smashingmagazine.com/2008/11/18/10-advanced-php-tips-to-improve-yourprogamming/ 7. http://net.tutsplus.com/tutorials/php/10-principles-of-the-php-masters/ 8. http://hungred.com/useful-information/php-micro-optimization-tips/ 9. http://www.nerdparadise.com/tech/php/10tips/

1|Page

PHP Tips
1. http://mashable.com/2010/10/21/php-tips-for-beginners/ PHP is the language behind some of the most powerful and pervasive web applications around, including the ubiquitous Facebook and the unstoppable WordPress.

Learning a new language can be daunting, so weve tapped a few PHP experts for their advice for novice PHP coders (stay tuned for an intermediate/advanced selection of tips, coming up in a couple weeks).

If youre a new PHP developer (or an old pro), be sure to leave a note in the comments and let us and other readers know what specific steps youve taken thats made learning the language easier for you. 1. Elizabeth Naramore: Start with OOP

Naramore is a SourceForge employee and founded PHPWomen.org. For total beginners, she recommends getting a thorough background in object-oriented programming (OO) before diving straight into PHP.

If youre coming from a non-tech industry, take the time to learn solid principles of software development. Things like object-oriented programming, test driven development, version control, debugging, design patterns, etc.

If youve tried and cant solve your problem, dont be afraid to ask. The PHP community in general is very helpful and friendly, and there are countless resources for the beginner available online. Entrench yourself in a community, whether it be a local user group, an open source project community, or an IRC channel like #phpc on freenode. 2. Keith Casey: Google It

Casey founded a software shop and does a lot of work in the unconference circuit.

His advice centers around finding your place in the PHP community and following an increasingly important dictum: Google before you ask. 2|Page

PHP Tips

Connect with a Users Group right now. There are PHP Groups all over the world where smart people gather to chat, explore ideas, and help one another.

Remember to try a Google search before asking questions. No one likes lazy. 3. Eamon Leonard: Join Open Source Projects

Leonard runs Ireland-based software company echolibre and co-founded CloudSplit, a real-time analytics service for cloud computing. Like many of his peers, he recommends trying your hand at opensource projects, even as a beginner.

Get involved in open source as soon as you come to grips with the basics This gives one access to source code and a chance to learn from industry veterans.

Finding and documenting reproducible bugs is a time consuming task, and one that would be greatly appreciated by any open source team When it comes to hiring developers to work with us, we would value someones potential contribution to our company a lot more if they have worked on an OSS project. 4. Lorna Jane Mitchell: Just Do It

Lornajane, as Mitchell is more commonly known online, is a PHP consultant, developer, writer and speaker.

She gives a word of advice quite commonly heard in hacking circles: Just do it.

Jump in! PHP is a really accessible language and fast to develop in. The best way to find out if something can be done that way is to try.

3|Page

PHP Tips
Anyone can program PHP. The low entry barrier means that there is a lot of bad PHP in the world. But bad PHP that works is useful even if it isnt pretty. Personally I think that if you can solve your problems with PHP, then you should get on and do it, even if it isnt perfect. 5. Chris Cornutt: Avoid Coding Burnout

Cornutt runs PHPDeveloper.org and Joind.in and has been using PHP since 1998. In his advice to baby PHP devs, he cautions against coding fatigue and burnout.

I think new developers get overwhelmed too easily Beginners like the language and they hack away with the just make it work mentality, but I dare say more than half stop there.

Try to find a mentor that can guide you through some of these early steps. It makes worlds of difference when you have someone real to talk to. IRC is a good option, but a go-to person is so much better.

Thankfully, they also have the entire web at their disposal with loads of PHP sites and examples to help them through the tough spots. Some of the examples are good, some not so much, but theyll come to learn those over time. PHP development, like anything else, is a skill that has to be honed you cant just jump into the middle and be an expert overnight. 6. Abraham Williams: Try Drupal

Williams is a developer and self-styled hacker advocate. He, too, advises new PHP coders to jump into a coding project, giving preference to open source work.

Find a quality project or community (preferably open source oriented) to contribute to. Get to know the code, the people and the customs. Not only will you learn from experienced developers, but the maintainers have a vested interest in quality code and a friendly community. They will be more than willing to recommend code improvements in patches and even how to be a better community member.

I suggest the Drupal project as a good starting point. It is mature, has a epic community, a great growth rate and lots of jobs for good Drupal developers. 4|Page

PHP Tips
7. Demian Turner: Study Seasoned Coders

Turner has been working with web and open source projects since 1996. He runs PHPKitchen.com and was a recent Seedcamp finalist.

He gave us a ton of great advice for new PHP developers, advice that can save time, make for better code and help sustain your interest in coding.

Read the code of seasoned devs; theres always a better, cleaner way to do things. Dont reinvent any wheels; you will always have more than enough to program; use reputable libraries whenever you can avoid writing the code yourself.

Ensure your code is human readable; if you cant understand it six months later, how will it be for other devs?

Always try and simplify your interfaces; its much more difficult to write simpler code, but consistent refactoring will save you a lot of time and headaches when it comes to maintenance.

Finally, read up on some of the great programmers and find out how they stayed passionate about the art of programming so many years later. 8. Stuart Herbert: Know Test-Driven Development, Encapsulation and Source Control

Herbert has been coding PHP since 1999; hes been writing about PHP for several years and has contributed greatly to Gentoo Linux.

For new PHP devs, he advises, Learn about test-driven development and encapsulation. Once you get the hang of it, youll ship code quicker, and whoever inherits your code will thank you for it.

Oh, and learn about source control; its never optional! 5|Page

PHP Tips

He also says the languages biggest strength is the fantastic documentation available at PHP.net for free. With certain other languages, you need to go out and buy the docs as books, but not with PHP. 9. Maggie Nelson: Read Up on Data Storage

Nelson is a PHP developer currently employed by Flickr.

She tells PHP newbies to start leanring about data storage early in their careers.

In many cases, youll use PHP for web applications. Compelling web apps tend to be the ones that use data in unexpected ways or in ways that solve everyday problems. If youre just starting with PHP and this is your first language ever, spend a day or two reading up on data storage and perhaps learn some SQL along the way as well. PHP is known for playing very well with databases. Check out MySQL, other relational databases and venture out to a few NoSQL data storage solutions.

Write all the code from scratch for at least one application. The PHP world offers many great frameworks that can easily abstract away data access, but always be sure that you really understand how the data is actually manipulated behind the scenes! 10. Michael Maclean: Learn about Security

Maclean is a PHP and Python developer based in the Outer Hebrides in Scotland.

He says, PHPs pretty easy to get going with, which is why so many people use it, but I think its important to have a look at what people whove been using it for a while are doing. Rather than writing everything from scratch, check out a couple of frameworks, which will probably give you a bit of a head start.

The other thing to do is learn about security. PHPs got a bit of a bad rep for that in the past, which is a bit of a side-effect of its ease of use. There are many resources online and in print on how to avoid

6|Page

PHP Tips
security problems. Check out the books by Chris Shiflett and Ilia Alshanetsky who also have information about that online. 2. http://www.phpbuilder.com/columns/vaska20050722.php3 I wish I had known these 10 tips the day I started working with PHP. Instead of learning them through painstaking process, I could have been on my way to becoming a PHP programmer even sooner! This article is presented in two parts and is intended for folks who are new to PHP. Tip 1: MySQL Connection Class The majority of web applications I've worked with over the past year have used some variation of this connection class:

class DB { function DB() { $this->host = "localhost"; // your host $this->db = "myDatabase"; // your database $this->user = "root"; // your username $this->pass = "mysql"; // your password

$this->link = mysql_connect($this->host, $this->user, $this->pass); mysql_select_db($this->db); } }

// calls it to action $db = new $DB;

7|Page

PHP Tips
Simply edit the variables and include this in your files. This doesn't require any knowledge or special understanding to use. Once you've added it to your repertoire, you won't likely need to create a new connection class any time soon. Now you can get to work and quickly connect to your database without a lot of extra markup:

$result = mysql_query("SELECT * FROM table ORDER BY id ASC LIMIT 0,10");

More information can be found in the manual--be sure you read the comments: http://www.php.net/mysql_connect/ Tip 2: Dealing with Magic Quotes PHP "automagically" can apply slashes to your $_POST data for security purposes. It's an important measure to prevent SQL injections. However, slashes in your scripts can wreak havoc. This is an easy method for dealing with them. The way to handle the slashes is to strip them from our variables. However, what if the magic quotes directive is not enabled?

function magicQuotes($post) {

if (get_magic_quotes_gpc()) { if (is_array($post) { return array_map('stripslashes',$post); } else { return stripslashes($post); } } else { return; // magic quotes are not ON so we do nothing }

} 8|Page

PHP Tips

The script above checks to see if magic quotes is enabled. If they are, it will determine if your $_POST data is an array (which it likely is) and then it will strip the slashes accordingly. Understand that this is not true 'validation'. Be sure to validate all your user-submitted data with regular expressions (which is the most common way to do so). More information about magic quotes: http://www.php.net/ magic_quotes/ More information about SQL injection: http://www.php.net/manual/en/security.database.sqlinjection.php/ More information about regular expressions: http://www.php.net/pcre/ Tip 3: Safely Query Database with mysql_real_escape_string When you are ready to query your database you will need to escape special characters (quotes for instance) for safety's sake by adding slashes. We apply these before we insert variables into our database. Once again, we need to determine which version of PHP you are running first:

function escapeString($post) {

if (phpversion() >= '4.3.0') { return array_map('mysql_real_escape_string',$post); } else { return array_map('mysql_escape_string',$post); }

More information about mysql_real_escape_string: http://www.php.net/ mysql_real_escape_string/ More information about SQL injection: http://php.belnet.be/manual/en/security.database.sqlinjection.php Tip 4: Debugging 9|Page

PHP Tips
If you search the forum there are many good threads with rules about debugging. The single most important thing you can do is ask PHP to report errors and notices to you by adding this line at the beginning of your scripts:

error_reporting(E_ALL);

This will keep you in line as you learn by printing out errors to your screen. The most common error that E_ALL reports is not actually an error, but a notice for an "Undefined index". Typically, it means that you have not properly set your variable. It's easy to fix and keeps you programming correctly. Another convenient tool while working with queries is print_r(). If your query is returning null or strange results, simply place this after your query command and it will display all the contents of the $result array.

print_r($result); exit;

The exit command stops your script from executing any further so you can specifically review your query results. More information about error_reporting: http://www.php.net/ error_reporting/ More information about print_r; http://www.php.net/print_r/ Tip 5: Writing Functions (and Classes) Initially I thought that tackling functions and classes would be difficult--thankfully I was wrong. Writing a function is something I urge all newbies to start doing immediately--it's really that simple. You are instantly involved in understanding how to produce more efficient code in smaller pieces. Where you might have a line of code that reads like this:

if ($rs['prefix'] == 1) { $prfx = 'Mrs. '; } elseif ($rs['prefix'] == 2) { $prfx = 'Ms. ';

10 | P a g e

PHP Tips
} else { $prfx = 'Mr. '; }

echo $prfx.$rs['name'].' '.$rs['last_name'];

You could rewrite it like this in a function:

function makePrefix($prefix='') { if (!$prefix) return ''; if ($prefix == 1) return 'Mrs. '; if ($prefix == 2) return 'Ms. '; if ($prefix == 3) return 'Mr. '; }

echo makePrefix($rs['prefix']) . $rs['name'] . ' ' . $rs['last_name'];

Now that you've written this function, you can use it in many different projects! An easy way to describe classes is to think of it as a collection of functions that work together. Writing a good class requires an understanding of PHP 5's new OOP structure, but by writing functions you are well on your way to some of the greater powers of PHP. More information about writing functions: http:// www.php.net/manual/en/language.functions.php More information about writing classes: http:// www.php.net/manual/en/language.oop5.php Everything I've learned, more or less, came from the manual, trial and error and great help from the many fine people here at PHPBuilder. Good luck programming--and come back soon for Part 2 in this series! 11 | P a g e

PHP Tips
http://www.phpbuilder.com/columns/vaska20050812.php3 I wish I had known these 10 simple things the day I started working with PHP. This article is part II in the this series and is intended for newbies. The previous article is located here.

Tip 6: Single and double quotes


Single and double quotes confused me for some time and it really should not have. I see this quite often in the forum as well. It's very easy to understand that double quotes allow php to parse and single quotes do not. Here are some examples:
$var = $value; // ok $var = "$value"; // ok, but double quotes are not necessary $var = '$value'; // will not work (single quotes will not allow parsing) ('.' the period adds/connects variables, functions, etc. together. Oftentimes programmers will leave spaces around the ' . ' to make things easier to read.) $var = 'This is the ' . $value . ' of things.'; // ok - preferred technique $var = "This is the $value of things."; // ok, but harder to read/debug $var = 'This is the $value of things.'; // will not parse $value $var = This is the $value of things.; // error $var = $array['name']; // ok, generally the preferred technique $var = $array["name"]; // ok, but why use double quotes if they are not necessary? $var = "$array[name]"; // ok, but harder to read/debug - poor coding style $var = $var = coding $var = $var = 'Name: "Name: style "Name: "Name: ' . $array['name']; // ok - preferred technique $array[name]"; // ok, but harder to read/debug - poor $array["name"]"; // error $array['name']"; // error

exampleFunction($value); // ok exampleFunction("$value"); // ok, but double quotes are not necessary exampleFunction('$value'); // will not parse $value

Tip 7: Problems of style


It's a matter of style and convenience to produce your scripts in such a way that make them easy to read and debug. If you are using a programming editor that highlights your code it will be easy to identify the various parts. This may explain why you find syntax that looks rather confusing at first. Some examples:
$line = $result['name'] . ' ' . $result['last_name']; // ok - easy to read/debug $line = $result["name"] . ' ' . $result["last_name"]; // ok, but why use double quotes if they are not necessary? $line = "$result[name] $result[last_name]"; // ok - but much harder to read/debug - poor coding style $line = $result['name'] . ' ' . doSomething($result['last_name']); //

12 | P a g e

PHP Tips
ok - preferred method (using a function)

If you are working with any kind of a team and/or plan on allowing others access to your work in the future it's etiquette to try to make it accessible and easy on the eyes.

Tip 8: Ternary Operator


The ternary operator is similar to an if/else statement except that it's more streamlined. This is a traditional if/else statement:
if (empty($_POST['action'])) { $action = 'default'; } else { $action = $_POST['action']; }

This example of a ternary operator will produce the same result as the previous example using less space. It makes use of ? and : just like if and else.
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

Working with ternary operators do take a little more practice - be sure you test your work as you work through them. More information: http://www.php.net/ operators.comparison

Tip 9: Safe Queries


Safe queries are really a subject for a lengthier tutorial, but I'm going to try to make a simple presentation here. I'm using functions in this example as opposed to the more traditional class technique. A safe query will not return an error message that may reveal path information or give hackers accidental insider information. Certainly, security by obscurity is not an effective measure, but reducing error messages at the user end is desired once your site is launched. We use the connection class from the previous article and a few functions to make this happen. Our first function performs the actual query using msyql_query. If the query string is empty it will return false.
function safeQuery($query='') { global $db; if (!$query) return false; return mysql_query($query, $db->link); }

The next two sample functions are our means for performing queries. Note that our fetchArray() function will return an array of results while the fetchRow() function will simply return a row. If either function returns no results FALSE will be returned.
// returns an array of records function fetchArray($query='') { if ($result = safeQuery($query)) { if (mysql_num_rows($result) > 0) {

13 | P a g e

PHP Tips
while ($arr = mysql_fetch_assoc($result)) $rows[] = $arr; return $rows; } } return false; } // returns a single record function fetchRecord($query='') { if ($row = safeQuery($query)) { if (mysql_num_rows($row) > 0) { return mysql_fetch_assoc($row); } } return false; }

Now, with one simple line of code we can perform our query to return our predicted results.
$results = fetchArray("SELECT id,field1 FROM records"); // sample output results if (!$results) { echo 'No results.'; } else { // loop the data foreach ($results as $result) { echo $result['id'] . ' ' . $result['field1']; } }

With this approach you can also define your queries more specifically for INSERT, DELETE, etc. and/or for repetitive tasks. Once you have a group of functions you are comfortable with you can recycle them in other projects. If you understand how these safe query functions work then you are probably ready to explore the commonly used PEAR DB database abstraction class. This class, which is open source, will give you more flexibility, debugging features and it will work on more than just a MySQL database. A more complete tutorial regarding safe queries can be found at this site. Be sure to read the section regarding debugging your safe queries as well.

Tip 10: A Strategy for Success


And finally, I highly recommend using a pen, paper and plain english (or your language of preference) to work out your concepts first. Chances are that if you can explain what you need to do in plain language, you will both be able to explain the problem to others and ultimately solve your problem. You will be surprised how much easier it will be to program with a plan rather than making it up as you go along.

14 | P a g e

PHP Tips
Conclusion
For the most part, this collection of 10 things I wish I knew when I started using PHP are quite simple, but they should be considered building blocks. Additionally, some of the concepts presented are good examples of how you can build your own custom functions thus improving your speed and skill. Good luck programming!

15 | P a g e

PHP Tips
3. http://www.htmlgoodies.com/beyond/php/article.php/3907521/Top-10-PHP-Tips-for-Developers.htm I have always wanted to write an article like this, because I think about it all the time - what 10 things would I deem the most important to pass on to someone else? Well, after literally years of thought I think I have come up with the best list that I can think of. So, without further a do, let's get to it. 1) Go OOP

If you have not yet entered the realm of Object Oriented Programming, then you are at a disadvantage, and you are falling behind fast.

OOP is essentially a method of programming with the use of classes, or Objects, which tie like things together, remove the need for repetition of code and perform the basic tasks of production very simply. Objects are essentially classes that collect a bunch of functions together and wrap them in a wrapper that can be reused over and over again without the need to rewrite functionality or procedures every time you need to do something.

Procedural Programming works by following a routine from the top to the bottom of each page as the server reads every file on your server. With OOP, there could be one or two objects being instantiated, which, in turn could instantiate a few, a hundred or a thousand other objects which could all perform certain tasks depending on variables passed into the objects. OOP is faster, simpler, easier to debug, uses less server resources, less code, is faster loading and more logical to work with once you figure out the basic principles. Go OOP - It changed my development style forever. 2) Stay Away from Anything Ending With _once()

We all know that include() simply gives us a warning if it fails, while require() kills the script with a fatal error when it fails. What we don't forget is that include_once() and require_once() is extremely hard on server resources. There is nothing we can do about it, it's how PHP is set up. Just remember that these things kill your server resources, specially on a huge framework, and if you plan your code properly you won't even need it anyway. 3) Develop With Error Reporting On

16 | P a g e

PHP Tips
The very first thing you do when starting a new project is to turn error reporting to E_ALL, and you should only turn it off ten seconds before going to production mode. I do this with every project that I build and there is nothing better than running a project in full production mode and not even getting one error. Besides that, with error reporting on, you pick up any small errors that will eventually grow up to bite you in the... well, you get my point. 4) Use A Framework If You Need One

Ok, so Rasmus Lerdorf says you shouldn't use a framework because he could quite conclusively prove that a framework is much slower than normal PHP code when it came to printing a simple "Hello World" application. Two things to mention here though: you are not Rasmus Lerdorf and I bet you won't be building a "Hello World" application every time you program something. Frameworks that help you do the tedious things can help, although you will have to learn how the frameworks function first in order to make things simple, but that's the only real trade-off. Plus you stand less chance of writing bad code when someone else has written most of it for you, but let's pretend I didn't say that. 5) Use PHP's Inbuilt Functions

Ok, you want to count the amount of keys in an array? You can loop through the array and simply increment a value for each iteration, right? Or you can just use the built in PHP function count(), which does just what it should. PHP has many built-in functions that can do what you need them to, so check out the manual to make sure you are doing it in the best way possible. 6) Protect Your Database

The best and safest way is to use mysql_real_escape_string() for all database before it is added to the database. This function makes all strings safe in terms of quotes and other functions that can harm your database or contain malicious code, so use it to be sure you have taken the first step against protection of your data. Another thing you can do is validate all POST and GET strings, never use $_REQUEST, and make sure all form submitted data is of the right type and value before adding it to a database query. 7) Use POST Not GET

Ok, this isn't always possible, but when its really not necessary, don't use GET, use POST. The reason is simple - GET is simple to emulate, all I need to do is add something to my address bar and I can hack your project. Obviously GET is the easy way to do pagination and permalinks, but when using form submission especially, stay with POST, it's safer.

17 | P a g e

PHP Tips
8) Draw Before You Code

A good practice to get into is to wireframe your projects, even if you are just scribbling a few notes on a piece of paper. It is very important to actually give the mechanics of you application some thought before sitting down to start coding, because in the process of planning it you will actually iron out the difficulties in your head and avoid the major headache that comes with the facepalm when you realize that everything you just did is either wrong, not needed, or just silly. 9) Understand Your Project

An artist cannot draw something that he has not seen before. A singer cannot sing a song that he has not heard before. You cannot code a project that you do not fully understand. If you do not understand exactly what it needs to do, and how it needs to it, you cannot build it. 10) Code Code Code

If I could get one thing through to anyone reading this, this is it. You cannot become a good developer by reading. You cannot become a good developer by watching someone develop. The one and only tried and trusted method, is to actually write code. But - and here is the trick - build real things! Do not go and code something that you have no interest in, or will never use. Build what you like, and you will be excited and interested by it, and you will learn. Then, make it awesome, build upon it, and make it better.

18 | P a g e

PHP Tips
4. http://net.tutsplus.com/tutorials/php/quick-tip-7-super-handy-php-functions-for-beginners/ Have you ever taken a look at the list of functions available in PHP? I just counted 5025 on the PHP quick reference page. Granted, it depends on what extensions you have enabled, but still: thats one heap of functions! While I cant show you every one of them, if youre new to the language, Ill introduce you to seven really handy ones in this quick tip!

Function 1: array_rand

Lets start with a simple one. Ever want to get a random item out of an array? You might use rand or mt_rand to get a random number, passing 0 and the last index of the array as the min and max parameters; this will give you a random key that you can use to pull a value from your array.

However, theres a way thats a little bit quicker: array_rand. Just pass it your array, and it will return the random key. view plaincopy to clipboardprint?

$sites = ["Nettuts+", "Psdtuts+", "Mobiletuts+", "Mactuts+"]; $k = array_rand($sites); $sites[$k];

If you want more than one random value from the array, pass a second parameter identifying how many; youll get back an array of random keys. Function 2: strip_tags

Its not uncommon to accept larger chunks of text from a user: maybe as a comment or a bio. Of course, you probably dont want just any HTML tags to be allowed in that text, though, right? You dont want random JavaScript running, or perhaps your styling dictates they only use plain text. So, youll want to strip out the HTML tags they enter, using strip_tags:

19 | P a g e

PHP Tips
view plaincopy to clipboardprint?

$message = "<div> This is my bio </div>"; echo strip_tags($message); // "This is my bio"

Of course, you might want to allow certain tags, like <strong>, <em>, or <code>, for some simple styling; pass a string listing those as the second parameter: view plaincopy to clipboardprint?

$message = "<div> This is <strong>my</strong> bio </div>"; echo strip_tags($message, "<strong><em><code>"); // "This is <strong>my</strong> bio"

Function 3: strftime

Dates are a big part of any web apps, so you should be able to output them in any format you need. Its not hard to get a timestampyoull pull it from a database or use time(), maybebut how about formatting it? The strftime function can format that timestamp in any way youd like. Youll pass it a format string and the timestamp and get the date back out. view plaincopy to clipboardprint?

strftime("%B %d, %Y", time()); // July 28, 2012

Of course, its impossible to memorize all the formatting tokens, so I use the handy strfti.me to help me; give it a try, and youll love it, too. Function 4: basename

When working with a file, you usually want to get at it via its absolute path. However, if you need to display information about this file to the user, you probably just want to show them the file name, and 20 | P a g e

PHP Tips
not its whole path. Enter basename: this handy function will strip that path down to just the file name; just pass it the path as the parameter; if you want to get rid of a suffix, like a file extension, pass that suffix as the second parameter. view plaincopy to clipboardprint?

$path = "/some/long/path/to/the/special_file.txt"; $filename1 = basename($path); // special_file.txt $filename2 = basename($path, ".txt"); // special_file

Function 5: list

This ones pretty cool: lets say you have an array, and you want to assign its items to variables of their own. The list function makes this super-simple: view plaincopy to clipboardprint?

$array = ["Ellery", "Queen"]; list($first_name, $last_name) = $array;

echo $first_name; // Ellery echo $last_name; // Queen

As you can see, we just pass the new variable names as parameters to the list function and set that equal to the array. Its a bit different from the normal syntax, since the function call is on the left, but, yes, it does work. Heres a good example from the PHP docs (for explode): view plaincopy to clipboardprint?

$data = "foo:*:1023:1000::/home/foo:/bin/sh";

21 | P a g e

PHP Tips
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);

Function 6: range

If you ever need a list of numbers to iterate over, youll want to check out the range function. Just pass it a starting and ending number (or letter), and it will return an array of the numbers: view plaincopy to clipboardprint?

range(0, 10); // array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) range('a', 'f'); // array('a', 'b', 'c', 'd', 'e'. 'f');

As you can see, its an inclusive range, so both the numbers you define are included. You could also pass a step parameter to specify the increment between numbers: view plaincopy to clipboardprint?

range(2, 10, 2); // array(2, 4, 6, 8, 10);

Function 7: isset

Heres a handy way to check if a variable has been set: use the isset function. You just pass it a variable name, and it will return true if that variable exists, and is set to something other than NULL. view plaincopy to clipboardprint?

$name = "Joe";

isset($name); // true isset($age); // false 22 | P a g e

PHP Tips

Since this function also works with the items in array and associative arrays, this function is often used to check for the existence of specific keys on the $_GET and $_POST superglobal arrays: if a given value exists, youll do one thing; otherwise, youll do something else. For example, a search page might go something like this: view plaincopy to clipboardprint?

if(isset($_GET['query'])) { // get results and display them } else { // show some default content }

23 | P a g e

PHP Tips
5. http://www.wmtips.com/php/tips-optimizing-php-code.htm Here is the list of 43 short tips you can use for writing an optimized and more efficient PHP code:

If a method can be static, declare it static. Speed improvement is by a factor of 4. echo is faster than print. Use echo's multiple parameters instead of string concatenation. Set the maxvalue for your for-loops before and not in the loop. Unset your variables to free memory, especially large arrays. Avoid magic like __get, __set, __autoload require_once() is expensive Use full paths in includes and requires, less time spent on resolving the OS paths. If you need to find out the time when the script started executing, INSERT:CONTENT:END SERVER['REQUEST_TIME'] is preferred to time() See if you can use strncasecmp, strpbrk and stripos instead of regex str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4 If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments. It's better to use select statements than multi if, else if, statements. Error suppression with @ is very slow. Turn on apache's mod_deflate Close your database connections when you're done with them $row['id'] is 7 times faster than $row[id] Error messages are expensive

24 | P a g e

PHP Tips
Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function. Incrementing a global variable is 2 times slow than a local var. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance. Methods in derived classes run faster than ones defined in the base class. A function call with one parameter and an empty function body takes about the same time as doing 78 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations. Surrounding your string by ' instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string. When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & 25 | P a g e

PHP Tips
hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

Example: if (strlen($foo) < 5) { echo "Foo is too short"; }

vs.

if (!isset($foo{5})) { echo "Foo is too short"; }

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory. Do not implement every data structure as a class, arrays are useful, too Don't split methods too much, think, which code you will really re-use You can always split the code of a method later, when needed Make use of the countless predefined functions If you have very time consuming functions in your code, consider writing them as C extensions Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview 26 | P a g e

PHP Tips
mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80% Excellent Article about optimizing php by John Lim

27 | P a g e

PHP Tips
6. http://coding.smashingmagazine.com/2008/11/18/10-advanced-php-tips-to-improve-yourprogamming/

PHP programming has climbed rapidly since its humble beginnings in 1995. Since then, PHP has become the most popular programming language for Web applications. Many popular websites are powered by PHP, and an overwhelming majority of scripts and Web projects are built with the popular language. Because of PHPs huge popularity, it has become almost impossible for Web developers not to have at least a working knowledge of PHP. This tutorial is aimed at people who are just past the beginning stages of learning PHP and are ready to roll up their sleeves and get their hands dirty with the language. Listed below are 10 excellent techniques that PHP developers should learn and use every time they program. These tips will speed up proficiency and make the code much more responsive, cleaner and more optimized for performance.
(Smashing's side note: Have you already bought the brand new Smashing Book #3? The book introduces new practical techniques and a whole new mindset for progressive Web design. Get your book today!)

1. Use an SQL Injection Cheat Sheet

A list of common SQL injections. SQL injection is a nasty thing. An SQL injection is a security exploit that allows a hacker to dive into your database using a vulnerability in your code. While this article isnt about MySQL, many PHP programs use MySQL databases with PHP, so knowing what to avoid is handy if you want to write secure code. Furruh Mavituna has a very nifty SQL injection cheat sheet that has a section on vulnerabilities with PHP and MySQL. If you can avoid the practices the cheat sheet identifies, your code will be much less prone to scripting attacks.

2. Know the Difference Between Comparison Operators


28 | P a g e

PHP Tips

PHPs list of comparison operators. Comparison operators are a huge part of PHP, and some programmers may not be as well-versed in their differences as they ought. In fact, an article at I/O reader states that many PHP developers cant tell the differences right away between comparison operators. Tsk tsk. These are extremely useful and most PHPers cant tell the difference between == and ===. Essentially, == looks for equality, and by that PHP will generally try to coerce data into similar formats, eg: 1 == 1 (true), whereas === looks for identity: 1 === 1 (false). The usefulness of these operators should be immediately recognized for common functions such as strpos(). Since zero in PHP is analogous to FALSE it means that without this operator there would be no way to tell from the result of strpos() if something is at the beginning of a string or if strpos() failed to find anything. Obviously this has many applications elsewhere where returning zero is not equivalent to FALSE. Just to be clear, == looks for equality, and === looks for identity. You can see a list of the comparison operators on the PHP.net website.

3. Shortcut the else


It should be noted that tips 3 and 4 both might make the code slightly less readable. The emphasis for these tips is on speed and performance. If youd rather not sacrifice readability, then you might want to skip them.

29 | P a g e

PHP Tips
Anything that can be done to make the code simpler and smaller is usually a good practice. One such tip is to take the middleman out of else statements, so to speak. Christian Montoya has an excellent example of conserving characters with shorter else statements. Usual else statement:
1 if( this condition ) 2{ 3 $x = 5; 4} 5 else 6{ 7 $x = 10; 8}

If the $x is going to be 10 by default, just start with 10. No need to bother typing the else at all.
1 $x = 10; 2 if( this condition ) 3{ 4 $x = 5; 5}

While it may not seem like a huge difference in the space saved in the code, if there are a lot of else statements in your programming, it will definitely add up.

4. Drop those Brackets

30 | P a g e

PHP Tips

Dropping brackets saves space and time in your code. Much like using shortcuts when writing else functions, you can also save some characters in the code by dropping the brackets in a single expression following a control structure. Evolt.org has a handy example showcasing a bracket-less structure.
1 if ($gollum == 'halfling') { 2 $height --; 3}

This is the same as:


1 if ($gollum == 'halfling') $height --;

You can even use multiple instances:


1 if ($gollum == 'halfling') $height --; 2 else $height ++; 3 4 if ($frodo != 'dead') 5 echo 'Gosh darnit, roll again Sauron';

31 | P a g e

PHP Tips
6 7 foreach ($kill as $count) 8 echo 'Legolas strikes again, that makes' . $count . 'for me!';

5. Favour str_replace() over ereg_replace() and preg_replace()

Speed tests show that str_replace() is 61% faster. In terms of efficiency, str_replace() is much more efficient than regular expressions at replacing strings. In fact, according to Making the Web, str_replace() is 61% more efficient than regular expressions like ereg_replace() and preg_replace(). If youre using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace().

6. Use Ternary Operators


Instead of using an if/else statement altogether, consider using a ternary operator. PHP Value gives an excellent example of what a ternary operator looks like.
01 //PHP COde Example usage for: Ternary Operator 02 $todo = (empty($_POST[todo])) ? default : $_POST[todo]; 03 04 // The above is identical to this if/else statement 05 if (empty($_POST[todo])) {

32 | P a g e

PHP Tips
06 $action = default; 07 } else { 08 $action = $_POST[todo]; 09 } 10 ?>

The ternary operator frees up line space and makes your code less cluttered, making it easier to scan. Take care not to use more than one ternary operator in a single statement, as PHP doesnt always know what to do in those situations.

7. Memcached

Memcached is an excellent database caching system to use with PHP. While there are tons of caching options out there, Memcached keeps topping the list as the most efficient for database caching. Its not the easiest caching system to implement, but if youre going to build a website in PHP that uses a database, Memcached can certainly speed it up. The caching structure for Memcached was first built for the PHP-based blogging website LiveJournal. PHP.net has an excellent tutorial on installing and using memcached with your PHP projects.
33 | P a g e

PHP Tips
8. Use a Framework

CakePHP is one of the top PHP frameworks. You may not be able to use a PHP framework for every project you create, but frameworks like CakePHP, Zend, Symfony and CodeIgniter can greatly decrease the time spent developing a website. A Web framework is software that bundles with commonly needed functionality that can help speed up development. Frameworks help eliminate some of the overhead in developing Web applications and Web services. If you can use a framework to take care of the repetitive tasks in programming a website, youll develop at a much faster rate. The less you have to code, the less youll have to debug and test.

9. Use the Suppression Operator Correctly


The error suppression operator (or, in the PHP manual, the error control operator) is the @ symbol. When placed in front of an expression in PHP, it simply tells any errors that were generated from that expression to now show up. This variable is quite handy if youre not sure of a value and dont want the script to throw out errors when run. However, programmers often use the error suppression operator incorrectly. The @ operator is rather slow and can be costly if you need to write code with performance in mind. Michel Fortin has some excellent examples on how to sidestep the @ operator with alternative methods. Heres an example of how he used isset to replace the error suppression operator:
1 if (isset($albus)) 2 else $albert = $albus;

$albert = NULL;

34 | P a g e

PHP Tips
is equivalent to:
1 $albert = @$albus;

But while this second form is good syntax, it runs about two times slower. A better solution is to assign the variable by reference, which will not trigger any notice, like this:
1 $albert =& $albus;

Its important to note that these changes can have some accidental side effects and should be used only in performance-critical areas and places that arent going to be affected.

10. Use isset instead of strlen

Switching isset for strlen makes calls about five times faster. If youre going to be checking the length of a string, use isset instead of strlen. By using isset, your calls will be about five times quicker. It should also be noted that by using isset, your call will still be valid if the variable doesnt exist. The D-talk has an example of how to swap out isset for strlen: A while ago I had a discussion about the optimal way to determine a string length in PHP. The obvious way is to use strlen(). However to check the length of a minimal requirement its actually not that optimal to use strlen. The following is actually much faster (roughly 5 times) Its a small change but, like all the tips weve covered today, adds up to quicker, leaner code.

35 | P a g e

PHP Tips
7. http://net.tutsplus.com/tutorials/php/10-principles-of-the-php-masters/

With PHPs widespread adoption,its almost too easy to find a script or snippet to do exactly what you need. Unfortunately, theres no filter as to what is a good practice and whats, well not so good when writing a PHP script. We need trustworthy sources, who have proven they have a solid grasp on the best practices of PHP. We need PHP masters to show us the best principles to follow for high-grade PHP programming.

1. Use PHP Only When You Need it Rasmus Lerdorf


Theres no better resource than PHPs creator for knowing what PHP is capable of. Rasmus Lerdorf created PHP in 1995, and since then the language has spread like wildfire through the developer community, changing the face of the Internet. However, Rasmus didnt create PHP with that intent. PHP was created out of a need to solve web development problems. And as with many open source projects that have gone on to become popular, the motivation was never philosophical or even narcissistic. It was purely a case of needing a tool to solve real-world Web-related problems. In 1994 the options were fairly limited when it came to Web development tools. However, you cant use PHP for everything. Lerdorf is the first to admit that PHP is really just a tool in your toolbox, and that even PHP has limitations. Use the right tool for the job. I have run across companies that have completely bought into PHP, deploying it absolutely everywhere, but it was never meant to be a general-purpose language appropriate for every problem. It is most at home as the front-end scripting language for the Web. Trying to use PHP for everything isnt efficient, and it certainly isnt the best use of your time as a web developer. Dont be afraid to to use other languages if PHP isnt working out for your project.

36 | P a g e

PHP Tips

2. Use Many Tables With PHP and MYSQL for Scalability Matt Mullenweg
Nobody needs to question Matt Mullenwegs authority with PHP. He has, (alongside a rabid community), developed the most popular blogging system on the planet: WordPress. After creating WordPress, Matt and company launched the stellar WordPress.com, a free blogging site based on the WordPress MU code base blogging software for multiple blogs. At the time of this writing, WordPress.com hosts over 4 million blogs, and their users have written over 140,000 posts today. (You can see more interesting stats about WordPress.com usage here.) If anybody knows how to scale a website, its Matt Mullenweg. In 2006 Matt gave some insight into WordPress database structure and explained why WordPress MU uses a separate MySQL table for each blog, as opposed to using one giant monolithic table for all of the blogs.
We tested this approach for MU, but found it was too expensive to scale past a certain point. With monolithic structures you hit a wall based on your hardware. In MU users are divided and can be partitioned easily, for example on WordPress.com we have the users partitioned between 4096 databases, which allows you to scale very cheaply and efficiently to hundreds of thousands and even millions of users and extremely high levels of traffic.

Being able migrate the tables allows the code and ultimately the blogs to run much faster and scale easier. Alongside some heavy caching, and smart database usage, Matt has shown that extremely popular sites like Facebook and WordPress.com can run off of PHP and handle the incredible traffic load.

37 | P a g e

PHP Tips

3. Never, ever trust your users Dave Child


Dave Child is the brainchild (teehee) behind the recently renamed Added Bytes (previously ilovejackdaniels.com) website that featured Daves excellent cheat sheets for many programming languages. Daves worked for many development companies in the UK and has established himself as an authority in the programming world. Dave offers some sage advice when it comes to writing secure code in PHP: Dont trust your users. They just might hurt you. So the cardinal rule of all web development, and I cant stress it enough, is: Never, Ever, Trust Your Users. Assume every single piece of data your site collects from a user contains malicious code. Always. That includes data you think you have checked with client-side validation, for example using JavaScript. If you can manage that, youll be off to a good start. If PHP security is important to you, this single point is the most important to learn. Dave goes on to give specific examples of secure practices in parts one, two and three of his Writing Secure PHP series. But his ultimate takeaway is this: Finally, be completely and utterly paranoid. If you assume your site will never come under attack, or face any problems of any sort, then when something eventually does go wrong, you will be in massive amounts of trouble. If, on the other hand, you assume every single visitor to your site is out to get you and you are permanently at war, you will help yourself to keep your site secure, and be prepared in case things should go wrong.

38 | P a g e

PHP Tips

4. Invest in PHP Caching Ben Balbo


Ben Balbo has been writing for Site Point, a very well respected tutorial site for the likes of developers and designers. Hes on the committee for both the Melbourne PHP User Group and Open Source Developers Club, so he knows a thing or two about the language. Its no surprise with Bens background as a PHP developer and trainer that he recommends putting a little more thought and preparation into PHP caching. If you have a busy and predominantly static web sitesuch as a blogthats managed through a content management system, it will likely require little alteration, yet may benefit from huge performance improvements resulting from a small investment of your time. Setting up caching for a more complex site that generates content on a per-user basis, such as a portal or shopping cart system, will prove a little more tricky and time consuming, but the benefits are still clear. There are many different techniques for caching in PHP, and Ben touches on a few of the bigger ones in the article, like:

cached function calls setting expiry headers caching file downloads in IE template caching Cache_Lite

and many others. Because of the nature of dynamic languages like PHP, caching is critical to store those parts of the page that are accessed frequently and dont change often.

39 | P a g e

PHP Tips

5. Speed up PHP Development with an IDE, Templates and Snippets Chad Kieffer
When Chad Kieffer isnt busy rocking user interfaces and administering databases, hes giving expertise advice from his blog 2 tablespoons. Because of Chads wide field of expertise, hes often able to see the big picture that other programmers might not, specifically when it comes to the holistic approach that Chad takes to developing a website. He specializes in all aspects of the development process, so any insights he can provide with putting together an entire project is going to be useful. Chad believes that using an IDE like Eclipse PDT (Eclipses PHP development package) with a mixture of templates and snippets can really speed up the turnaround time on a project. Busy schedules, long to do lists, and deadlines make it tough for developers to get familiar with some of the advanced features their tools provide. This is a shame, because some features, like Eclipse Templates, can really reduce coding time and errors. Common sense says that any time you can automate a task, the quicker youll get the project done. The same holds true with Dans theory. By taking the time to create templates that youll use over and over, youll save tons of time automating the repetitive parts of coding. By using an IDE like Eclipse and the PDT package, youll find that your development time will incrementally speed up. The IDE will auto-close brackets, add those missing semicolons and even allow you to debug within the editor, without having to upload to the server. (Chad has a nifty tutorial on getting started with Eclipse PDT and the benefits of an IDE in general, if youre interested.)
40 | P a g e

PHP Tips

6. Make Better Use of PHPs Filter Functions Joey Sochacki


While Joey Sochacki may not be as big of a name as Matt Mullenweg in the PHP community, hes a seasoned web developer and shares tips that hes picked up along the way at his blog Devolio. Joey has found that even though there is a ton of filtering that has to happen when writing PHP code, not many programmers make use of PHPs filter functions. Filtering data. We all have to do it. Most, if not all of us, despise doing it. However, unbeknown to most are PHPs filter_* functions, that allow us to do all sorts of filtering and validation. Using PHPs filter_* functions, we can validate and sanitize data types, URLs, e-mail addresses, IP addresses, strip bad characters, and more, all with relative ease. Filtering can be tricky, but this guide can help immensely. With Joeys help youll learn how to install the filters and and filter nearly anything, taking advantage of the filtering power of PHP.

41 | P a g e

PHP Tips

7. Use a PHP Framework Josh Sharp


There has always been a debate as to whether to use a PHP framework like Zend, CakePHP, Code Igniter, or any other framework. There are upsides and downsides to using one, and many developers have their own opinions about whether or not to go down this road. Josh Sharp is a web developer who makes his bread and butter creating websites for clients. This is why you should trust him when he says its a good idea to use a PHP framework to save time and eliminate mistakes when programming. Why? Josh believes its because PHP is too easy to learn. But PHPs ease of use is also its downfall. Because there are less restrictions on the structure of the code you write, its much easier to write bad code. But there is a solution: use a framework. PHP frameworks help standardize how you program, and can save lots of time in the development process. You can read more about the benefit of using a PHP framework at Joshs blog.

42 | P a g e

PHP Tips

8. Dont use a PHP Framework Rasmus Lerdorf


Contrary to Joshs belief that one should use a PHP framework, Rasmus Lerdorf, the Godfather of PHP himself, believes that frameworks arent that great. Why? Because they perform much slower than simple PHP. During Rasmus presentation at Drupalcon 2008, Rasmus compared the response times to a PHP page with a simple Hello World example, and compared it to a few PHP frameworks (slides 24-32), and showed that PHP frameworks are much slower than straight PHP. You can listen or watch the entire presentation where Rasmus shows the performance losses with PHP frameworks. In short, Rasmus shows that performance takes a major hit when you use a PHP framework as opposed to using pure PHP.
[Note: If you have to use a PHP framework, Rasmus likes Code Igniter the best, as it is "least like a framework"]

43 | P a g e

PHP Tips

9. Use Batch Processing Jack D. Herrington


Jack Herrington is no stranger to PHP and the development world. On top of writing over 30 articles for the prestigious IBM developerWorks, Jack has also published programming books like PHP Hacks. Jack is a bona fide expert. Herrington recommends using batch processing and cron to tackle those tasks that can process in the background. Web users dont want to wait long for tasks to complete on the web. There are some jobs that take longer that are much more suited to being done in the background. Certainly, in some small cases, its a bit easier to fire off of a helper thread to handle small jobs. But its easy to see that with the use of conventional tools cron, MySQL, standard objectoriented PHP, and Pear::DB creating batch jobs in PHP applications is easy to do, easy to deploy, and easy to maintain. Jack believes in simplicity, and instead of using threading on servers, he uses the simple combination of cron, PHP and MySQL to process tasks in the background. Ive done both, and I think cron has the advantage of the Keep It Simple, Stupid (KISS) principle. It keeps the background processing simple. Instead of having a multithreaded jobprocessing application that runs forever and, thus, can never leak memory, you have a simple batch script that cron starts. The script determines whether theres anything to do, does it, then exits. No need to worry about memory leaks. No need to worry about a thread stalling or getting caught in an infinite loop.

44 | P a g e

PHP Tips

10. Turn on Error Reporting Immediately David Cummings


David Cummings runs his own software company that specializes in content management systems, and has won several awards. If anyone knows how to develop a PHP application efficiently, its Dave. David wrote in a SitePoint article about the two PHP tips he wished hed learned in the beginning. One of the tips: Turn on error reporting immediately. Itll save a great deal of time in the long run. The single most important thing I tell people who use PHP is to turn error reporting to its maximum level. Why would I want to do this? Generally the error reporting is set at a level that will hide many little things like:

declaring a variable ahead of time, referencing a variable that isnt available in that segment of code, or using a define that isnt set.

These factors might not seem like that big a deal until you develop structured or object oriented programs with functions and classes. Too often, writing code without error reporting turned up high would cost you hours as you scoured long functions that didnt work because a variable was misspelled or not accessible. Error reporting can make finding the reason for an error much easier. A tiny bug in the code can be quickly identified if PHPs error reporting is turned on high. Save yourself some time and hair pulling by letting PHP find your bugs for you.

45 | P a g e

PHP Tips
8. http://hungred.com/useful-information/php-micro-optimization-tips/

There are many ways to improve the way you write your PHP code. And we can easily increase the efficiency of our code just by putting in some effort during development. However, there might be some unknown information that you might not aware in PHP that can help improve your code. In this article, i will try to provide you with some tips that can serve as micro optimization for your code and could also add on to the list of knowledge that you have in PHP. We will also look at many benchmarking of these tips where possible!

Loop
Every program will required certain amount of loop. And loop is considered as efficiency killer if you have many nested loop (means loop in a loop) as one loop will required to run n times and if you have 1 nested loop, this means your program will have to run n2 times. Well, i think you can do the math. But we are not talking about this. There is something more interesting about loop in PHP. There are many ways we can define a loop in PHP. But how do you know which one is the best way to loop your data? Apparently, using a for loop is better than foreach and while loop if the maximum loop is pre-calculated outside the for loop! What do i mean? Basically is this.
1 #Worst than foreach and while loop 2 for($i =0; $i < count($array);$i++){ 3 echo 'This is bad, my friend'; 4} 5 6 #Better than foreach and while loop 7 $total = (int)count($array); 8 for($i =0; $i < $total;$i++){ 9 echo 'This is great, my friend'; 10 }

The above shows two different ways of writing a for loop. The first way includes the operation count into the loop while the second one pre-calculate the total number of loop outside it. The

46 | P a g e

PHP Tips
difference between these two is that the second doesnt run count operation n times while the first one did. You can find this VERY interesting benchmarking on loops on PHP.

Single Vs Double Quotes


Since i mentioned that benchmarking page on loops, it also includes the benchmark for single() and double() quotes. Now, between these two what is the best one to use? It really doesnt makes much differences. But i preferred to use single() quote because i dont have to press shift? Just kidding (not). Thats one of the reason why i use a single quote over the double one. But the other reason is that PHP will scan through double quote strings for any PHP variables (additional operation) and usually i dont mix my variables and strings into one. I usually use single quote instead. However, you might also have aware that if an empty string is declared using a single quote, it seems like there is a performance pitfall. You or I might want to take note of that. Basically, there is a dollar($) symbols in your string, try to avoid double quote unless its variable?

Pre increment vs Post increment


Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as
1 $i++; 2 $++i 3 $i+=1; 4 $i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isnt any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i cant really confirm this. Furthermore, it really doesnt makes a big differences towards normal programmers but may affect those who are working towards micro optimization. Nonetheless, many people do suggest pre over post increment in term of optimization.

Absolute Path VS Relative Path


Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesnt. Well, thats the reason why i use absolute path. But the real reason is that using absolute path eliminate
47 | P a g e

PHP Tips
the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

Echo Vs Print
Yes! I know, echo is better. But how much better? Interested to know? I am interested. So i went to dig a bit on the internet and found some useful information for benchmarking between these two! Its around 12%-20% faster using echo compare to print when there is no $ symbol in the printing string. And around 40-80% faster if there is an $ symbol used in a printing string! This really demonstrate the differences between the keyword $ symbol used in PHP.

Dot Vs Commas Concatenation


Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below
1 $a = '10 PHP programming '; 2 $b = 'Improvement Tips'; 3 #10 PHP Programming Improvement Tips 4 echo $a.$b;

I usually do the above. Instead of this,


1 $a = '10 PHP programming '; 2 $b = 'Improvement Tips'; 3 #10 PHP Programming Improvement Tips 4 echo $a,$b;

Well, between these two which is more efficient? If you did visit the link for benchmarking between echo and print, you might have aware on the exact same test, they also have performed test case for dot and commas. The result shows that dot is more preferable if there are no variables or $ symbol involved which is around 200% faster. On the other hand, commas will help to increase around 20%-35% efficiency when dealing with $ symbols.

str_replace vs preg_replace vs ereg_replace


Ok! We have 3 string search function in PHP. Out of these three functions, which do you think will run the fastest? Some of you might have know, str_replace will run faster. Reason?
48 | P a g e

PHP Tips
str_replace doesnt run any complex expression unlike preg_replace and ereg_replace. Well, maybe many of you might know that but it is not necessary always str_replace that runs fastest. If you have to call str_replace 5 times compare to preg_replace, which will run faster? (str_replace, of course) Wrong! preg_replace runs 86.99% faster than 5 str_replace function call! Basically, i also have such doubt and search for such benchmark. The benchmark really explains some doubts we have in these functions.

Find Timestamp
When you want to find out the time when your script starts running in order to get that timestamp to store it into your database. The first thing you do is to fire up your Google and search for some PHP function. Well, after PHP5 you do not have to do that. After PHP 5 you can easily retrieve the execution timestamp of your script by using
1 $_SERVER['REQUEST_TIME']

This could really save some time digging for something that already exist within your reach.

explode Vs preg_split
Well, when you want to split a string what do you use in PHP? I usually used explode because it support even PHP4.0 and thats also what i was taught by my ex-colleagues. The answer in term of efficiency is explode. Split supports regular express and this makes it quite the same comparison between str_replace and preg_replace, anything that have regular expression support will usually be a bit more slower than those that doesnt support it. It took around 20.563% faster using explode in PHP.

Other Benchmarks
I believe this list can go on forever with such great benchmarking site i found. It basically shows you most of the benchmarking between PHP functions or those articles that claim whatever stuff is better than the other in PHP but doesnt provide you with any real evidence on their article. In this article, hopefully i have provided you with the necessary information for you to perform some micro optimization and also other more of such optimization through the benchmarking site.

Summary
I believe many of you have see all these information floating around the internet. But the only differences i see is that they dont really provides you with the real interesting part of this article, that is the benchmark of each test. This article really help me a lot with all the figures and testing given by all these great benchmarking site. Hopefully it also gives you the same result. P.S: Most of these benchmark sites are run on real-time.
49 | P a g e

PHP Tips

9. http://www.nerdparadise.com/tech/php/10tips/

Here are a few things worth mentioning that I've figured out during my years of writing PHPbased websites. Some of these might be obvious but are worth re-iterating. Others are things that I didn't consciously consider until learning the hard way sometimes multiple times.

#10 - Never use MySQL commands directly


Ever. Create a database object. This object ought to hold a reference to the MySQL connection and have functions for select, delete, update, and insert. Even if you're lazy and make these functions all just take in a string for SQL, this allows you the opportunity to have different return values. Obviously the Select function will return the table results of query, however there are functions called mysql_affected_rows and mysql_insert_id. mysql_affected_rows returns the number of rows affected by an update or delete query given a MySQL connection object. mysql_insert_id returns the primary key of the last inserted row. Both of these are incredibly useful but are silly to put inline in your code everywhere. $new_item_id = $db->insert("some query"); $update_success = $db->update("some query") > 0;

#9 - Create an underlying API from the get go


There comes a time in every PHP website's lifecycle where you want to go from a classical pageby-page layout to an AJAX or service-based presentation. To create a service API, you need to create each task a user could possibly do as a separate page. This becomes trivial if you created this from the start. If every individual task is a nice clean function call, then creating a public API for this is a simple matter of creating a bunch of pages that basically have half a dozen lines in them calling that function and printing out the results. Which brings us to the next point...

#8 - Actually use functions


PHP is a terrible language. There. I said it. Sometimes it's just really tempting to write a whole bunch of code from top to bottom because it's fast and easy in PHP. Bad. Take the time to figure out where there are natural separations in your logic for generating a page. Put those into functions. Group functions by theme into separate files then include those files from others. And while I'm talking about natural separations in logic...

#7 - Generate pages in two passes (data -> view)


50 | P a g e

PHP Tips
The following is too terribly common: $entries = $db>query("some select query to get a bunch of data"); for ($i = 0; $i < mysql_num_rows($entries); ++$i) { $entry = mysql_fetch_array($entries); echo blah blah blah $entry['foo'] blah blah $entry['meow'] bla h $entry['whatever']; }

Perhaps if you're simply showing some sort of tabular data, this canonical approach is okay. But for anything more complicated, it's worth it to create some sort of intermediate data structure. SQL tables don't always map nicely to how the data will ultimately be displayed. The data structure you generate ought to be the most logical structure that corresponds to what you're trying to do. For example, any tree based UI. Suppose you have some sort of discussion topic that has posts in multiple threads that go off in different tangential directions in a hierarchical tree. Tables don't make good trees. Suppose there's a table called 'topic_post' with columns for post ID, topic ID, parent post ID, text, and time. Here is some sample code to easily display this: $posts_from_db = $db->query(" SELECT `post_id`, `topic_id`, `parent_post_id`, `text` FROM `topic_post` WHERE `topic_id` = $topic ORDER BY `time` "); $posts_by_id = array(); $post_ids = array(); $root_post_id = 0; // create a lookup table by ID and list of ID's for ($i = 0; $i < mysql_num_rows($posts_from_db); ++$i) { $post = mysql_fetch_array($posts_from_db); $post['children'] = array(); $posts_by_id[$post['post_id'] = $post; array_push($post_ids, $post['post_id']); } // go through all posts and add them to their corresponding pare nt
51 | P a g e

PHP Tips
foreach ($posts_ids as $id) { $parent_id = $posts_by_id[$id]['parent_post_id']; if ($parent_id > 0) // assume in our system, a parent ID indic ates { array_push($posts_by_id[$parent_id]['children'], $id); } else { $root_post_id = $id; } } // since we're dealing with natrually recursive data, write a re cursive function to display it function show_post($post_id, $all_posts) { $post = $all_posts[$post_id]; echo '<div style="border:1px solid #000;">'.nl2br(htmlspecialc hars($post['text'])).'</div>'; if (count($post['children'] > 0)) { echo '<div style="padding-left:50px;">'; foreach ($post['children'] as $child_id) { show_post($child_id, $all_posts); } echo '</div>'; } } if ($root_post_id > 0) { show_post($root_post_id, $posts_by_id); }

Doing a basic loop that iterates through the results once makes many useful tools such as the recursion used here impossible.

#6 - Redirect forms to their originating pages


When I first started writing PHP, I tended to have forms as two pages. A page with the form on it and the page that processed the form/showed error messages if something went wrong. If there

52 | P a g e

PHP Tips
was an error in the data the user entered, I would display the error message and force the user to go back to the previous page to fix it. Nasty. The better solution is to redirect to the same page. $errors = array(); $form_submitted = isset($_POST['submit']); $show_form = true; if ($form_submitted) { // check for errors. // add any error messages to $errors if (count($errors) == 0) { // do SQL magic or whatnot $show_form = false; } else { echo "The following errors were encountered: <br />".implode ("<br />", $errors); $show_form = true; } } if ($show_form) { echo '<form action="this page" method="post"> ... </form>'; }

#5 - Email Assertions
When developing client-side software, typically a debug build will throw assertions if something goes remotely wrong and the programmer wants to know about it. In PHP it's a little more difficult. Sure, you can have echo statements surrounded by if statements that only display when it sees your ID. But there are random people out there viewing random pages in odd ways. For example, each time I rewrite NP there tends to be quite a few broken links across the site and they're almost impossible to track down. Finally, I added a line of code to send me an email message each time a 404 page was reached and the URL the user was trying to view and which page they came from. Of course the first day I got hundreds of emails. But most of them were from about 3 or 4 high-traffic broken links. I fixed those few links (and for the ones originating from outside NP, I added appropriate redirects) and suddenly, the number of 404's dropped about 90%. Way more effective than just going through all the site content and hoping I find all broken links.

53 | P a g e

PHP Tips

#4 - Do bookkeeping
Even powerful statistic and analysis tools like Google Analytics appears weak against the power you have in writing your own tracking system. You're not just limited to figuring out which pages are most popular, but you can also figure out what the heck it is your users spend their time doing. What does the typical user do? What pages do they visit and in what order? A few use cases can help you greatly optimize your page layout and content delivery.

#3 - Never use ORDER BY RAND() in MySQL


If you really must find a random entry in a database with more than a few hundred entries, do so using some heuristic or trick other than using ORDER BY RAND() LIMIT 1. This could be picking a random index and selecting the first entry greater than that. Do something like that because that can use an index to sort your results. When you sort results with an index, the sorting has already been done and the results are usually instantaneous. If you sort by RAND(), then the database has to generate a random number for each entry and compares each entry with every other entry using a traditional non-linear sorting algorithm. This is painfully slow and can actually cripple any query in a table with more than a few hundred entries. Even though most proprietary flavors of SQL have mecahnisms to do this quickly, MySQL just isn't smart enough to see the "LIMIT 1" at the end of the query and think to itself, "oh, I should just pick one at random". It sorts each entry. So you have to come up with something better than RAND().

#2 - Have an activation bit in the user table


I'm not sure why people register an account and then don't log in. This is extremely common. On some of my sites, the fraction of users that have never logged on is about 50% of the total entries in the user table. This is simply wasted space. Add a boolean column to your user table called has_ever_logged_on or some such with a default value of 0. When a user logs on, set it to 1. Then periodically, clear out all the old entries of people that never used their account. The extra space that 1 column uses definitely will pay for itself. If you have a last_login_time that's initialized to 0, you could re-purpose that for this function, too.

#1 - Security through obscurity never works


Everyone is looking for interesting things at interesting URL's. They're out to get you. If you have an admin panel at an obscure URL, assume someone will find it. Even if it's super obscure there's still a chance someone will find it via browser history or other mishaps. If you have something secure, go through the trouble of creating a password protected log-in system.

54 | P a g e

PHP Tips

55 | P a g e

You might also like