50+ PHP Tricks and Tips for Beginners & Developers

PHP is most useful language in making blogs and website, it have a lot of functions which can be used to derive even more custom functions. We have gathered most useful PHP Tricks and Tips for beginners and even Developers.These PHP Tricks makes your coding productive and more effective.

50+ PHP Tricks and Tips for Beginners

List of PHP Tricks and Tips

1. echo is faster than print.

2. Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.

3. Use sprintf instead of variables contained in double quotes, it’s about 10x faster.

4. Use echo’s multiple parameters (or stacked) instead of string concatenation.

5. Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.

6. Unset or null your variables to free memory, especially large arrays.

7. Avoid magic like __get, __set, __autoload.

8. Use require() instead of require_once() where possible.

9. Use full paths in includes and requires, less time spent on resolving the OS paths.

10. require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.

11. Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().

12. PCRE regex is quicker than EREG, but always see if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead.

13. When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.

14. str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace.

15. “else if” statements are faster than select statements aka case/switch.

16. Error suppression with @ is very slow.

17. To reduce bandwidth usage turn on mod_deflate in Apache v2 or for Apache v1 try mod_gzip.

18. Close your database connections when you’re done with them.

19. $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.

20. Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags.

21. Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.

22. PHP scripts are be served at 2-10 times slower by Apache httpd than a static page. Try to use static pages instead of server side scripts.

23. PHP scripts (unless cached) are compiled on the fly every time you call them. Install a PHP caching product (such as memcached or eAccelerator or Turck MMCache) to typically increase performance by 25-100% by removing compile times. You can even setup eAccelerator on cPanel using EasyApache3.

24. An alternative caching technique when you have pages that don’t change too frequently is to cache the HTML output of your PHP pages. Try Smarty or Cache Lite.

25. Use isset where possible in replace of strlen. (ie: if (strlen($foo) < 5) { echo “Foo is too short”; } vs. if (!isset($foo{5})) { echo “Foo is too short”; } ).

26. ++$i is faster than $ i++, so use pre-increment where possible.

27. Make use of the countless predefined functions of PHP, don’t attempt to build your own as the native ones will be far quicker; if you have very time and resource consuming functions, consider writing them as C extensions or modules.

28. 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.

29. Document your code.

30. Learn the difference between good and bad code.

31. Stick to coding standards, it will make it easier for you to understand other people’s code and other people will be able to understand yours.

32. Separate code, content and presentation: keep your PHP code separate from your HTML.

33. Don’t bother using complex template systems such as Smarty, use the one that’s included in PHP already, see ob_get_contents and extract, and simply pull the data from your database.

34. Never trust variables coming from user land (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML.

35. For security reasons never have anything that could expose information about paths, extensions and configuration, such as display_errors or phpinfo() in your webroot.

36. Turn off register_globals (it’s disabled by default for a reason!). No script at production level should need this enabled as it is a security risk. Fix any scripts that require it on, and fix any scripts that require it off using unregister_globals(). Do this now, as it’s set to be removed in PHP6.

37. Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5 hash.

38. Use ip2long() and long2ip() to store IP addresses as integers instead of strings.

39. You can avoid reinventing the wheel by using the PEAR project, giving you existing code of a high standard.

40. When using header(’Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible.

41. In OOP, if a method can be a static method, declare it static. Speed improvement is by a factor of 4..

42. Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable.

43. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

44. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

45. Just declaring a global variable without using it in a function slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.

46. 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.

47. Methods in derived classes run faster than ones defined in the base class.

48. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.

49. Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory.

50. Never trust user data, escape your strings that you use in SQL queries using mysql_real_escape_string, instead of mysql_escape_string or addslashes. Also note that if magic_quotes_gpc is enabled you should use stripslashes first.

51. Avoid the PHP mail() function header injection issue.

52. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.

53. RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English.

These are some of the PHP Tricks and Tips which can be very useful for those who just started learning the PHP language, and also for those who are developing since a good time. RTFM is the most efficient way to learn PHP though.

Comments

  1. Thank you for sharing such a wonderful post. Great way to make first 500$ from your blog. Well you can make many more. The first point you have mentioned is Google Adsense. Well only Adsense can give you 500 USD. And you can earn many ore fro the other ways you have mentioned. Thank you for sharing the article.

    Reply
  2. Pingback: Wordpress Plugin Development Guide | HotWpPlugin.com

  3. Pingback: blog o seo » Blog Archive » How to Track Blog's SEO Performance and Optimization

  4. Awesome post, these php tips and tricks helps a lot for all new php developer and from it, i also got some php tips and tricks which i doesn’t know till at all.

    Reply
  5. Pingback: Tweet-Parade (no.25 June 2012) | gonzoblog.nl

  6. Great tips, but i think you should change point 37. A simple md5 hash is not really sophisticated enough in the world we live in.

    Reply
  7. Soo sexy wallpapers and all wallpapers are vry good..
    Please if u dnt mind send some beautiful wallpapers on my email..

    Reply
  8. Pingback: How to Backup WordPress Database, Posts and Files | Design News

  9. Nice sharing.I enjoyed reading this post.This will give an idea for everyone on what’s happening on the web designing. I really loved these design resources. Thanks for sharing.

    Reply
  10. Great post… It is indeed very important that you store your backups outside your hosting account and that you workout a great backup strategy for automatic backups…

    I’ve described a good mix of daily, weekly and monthly backups with auto-deletion of old backup archives in my WordPress Backup article.

    Although I use a different plugin the principles are the same…

    Just my two cents… keep up the great work!

    Reply
  11. Pingback: 20 Easy Photoshop Text Tutorials for Beginners

  12. Pingback: Des pixels et du code #16 - Stéphanie Walter : Webdesign - intégration web

  13. nr.15
    if/else is faster than switch, you´re right, I did some tests,
    but you should consider in which case to use switch.

    I´ve cycled it, testing 10,1000,100000 and 1milion cycles and result is:
    in 100k cycles you get 0,13s diference on local machine (on outside server, you should get less diference).

    So you should consider using if/else of switch. I prefer using switch because of cleaner code. Using 1 switch, 2 switch, even 100 switch instead of if/else … it doesn´t matter, it´s meaningless.

    Reply
  14. nr.26
    i run test now,
    with $i++ and ++$i

    it´s simple – number 26 is meaningless until you want to use more than 10mil. cycles.
    And diference ?

    10mil cycles with $i++ 2.67448 s
    10mil cycles with ++$i 2.605528 s

    Reply
  15. Pingback: The New iPhone 5 Concept Designs and Looks | Design News

  16. Really nice quotes are here.Specially this one Designers have a dual duty; contractually to their clients and morally to the later users and recipients of their work.
    — Hans Höger
    Thanks for sharing and creating.

    Reply
  17. Pingback: 10 HD Abstract Art Wallpapers for Desktop

  18. Pingback: 30 Motivational Quotes for Designers from Designers | Design News

  19. Pingback: Homepage

  20. Pingback: 10 HD Abstract Art Wallpapers for Desktop | Design News

  21. Software development is comprised of cyclical free markets driven by creativity that produces benefits to others and new wealth for those who persevere to be in the right place at the right time with the right idea implemented with many lines of code and a few pretty pictures.

    Architecture is fascism, nepotism and racism that can produce great buildings and great places implemented with many pretty pictures and a few line drawings credited to someone other than those whose ideas and works produced the results that are actually constructed by others..

    I know what I love and I love what I know.
    Win, lose or draw its the bits and bytes from here on out…

    Reply
  22. I am glad you gathered these nice quote. Sometimes I think even designers don’t remember any more why they design and it became a comodity or a craft to make money out of it.
    Loved this one: The life of a designer is a life of fight: fight against the ugliness.

    — Massimo Vignelli
    Again thanks for putting this together

    Reply
  23. Pingback: Tweet Heat - The hottest Tweets of the Month [June 2012] | Inspired Magazine

  24. To be honestly I haven’t optimized my blog for 404 pages error.Now I’m going to optimize 404 error pages in my blog :) Thanks for this technique.

    Reply
  25. 24. (…) Try Smarty or Cache Lite.
    33. Don’t bother using complex template systems such as Smarty

    ok.

    (i’d personally just delete the #33; smarty (or other templating systems) has a lot of advantages comparing to the ob_ functions…)

    Reply
  26. Pingback: Tajuzzaman#Bookmark 01 - Pengguna wordpress dan mobile app developer check it out! - Tajuzzaman

  27. Pingback: Blogspot vs Wordpress - What is Best Blogging Platform?

  28. Pingback: iPhone 5 Release Date, Rumors and Price

  29. Pingback: Get a Facebook Page and ROCK YOUR TIMELINE!

  30. Hi DesignSkew.com,
    Thank you for this very useful information, and for share it!
    I have a very basic question as well. Where exactly do i have to put the snippets? You say in htaccess file and rest to be in functions.php, but “where exactly”, after what?
    Sorry for my low level, and thank you again for this wonderful article. ;-)

    Reply
    • Its fine, I feel good to help newbies, exactly I can’t tell because it is different for different theme. But in most condition, you can try adding the snippets in the bottom of the functions.php file, and same for htaccess, in the bottom of the file.

      Also, don’t forget not to leave any blank line in the end of functions.php file.

      Reply
  31. Hey, I really like your Blog. Could you put up some more webdesigns?
    TheDesignInspiration is the best in my opinion, but it may be considered to the webpages theme.

    Reply
  32. Pingback: iPhone PSD Template [GUI] Download | Design News

  33. Pingback: 5 Powerful WordPress Hacks to Improve SEO Ranking | Daily Serps

  34. Pingback: 10 New Macbook Pro Retina Display Wallpapers

  35. Pingback: How to Create Android Apps Free Online | Design News

  36. Pingback: Showcasing World's Most Creative Photo Gallery

  37. Pingback: The Dark Knight Rises Wallpaper and Posters

  38. Pingback: The Dark Knight Rises Wallpaper and Posters

  39. Pingback: The Dark Knight Rises Wallpaper and Posters

  40. Pingback: Free Android Music Player with Beautiful UI | Design News

  41. For novice bloggers- I guess Blogger is still rocking as a best blogging platform -reason being its simple, easy to use and write,good visibility in SERP (Google supports Blogger blogs)

    For Intermediate and expert level bloggers -WordPress and Joomla as these are CMS based blogging platforms and come with lot of in-built SEO coding and techniques.

    For professional bloggers -TypePad is also a very good option if you could spend around $15 per month to subscribe its sleek and smart blogging platform

    Reply
  42. Pingback: Awesome, Best and Cool Facebook Timeline Covers | Design News

  43. Pingback: 10 Most Beautiful Paintings in the World | Design News

  44. Pingback: 70 Must Read Motivational and Visualised Quotes. - Pillaticos

  45. first of all i would like to know that it’s paid hosting or free i tried the free hosting of zyma but they banned my free account without any reason so i returned to freehostia (free hosting) but they only have 250 mb space although all other features are good so if you are giving paid hosting plan then i really like to have as right now i am running my site on free hosting and my traffic is also increasding like hell and due to 6gb bandwidth limitation sometimes my site is remain offline.I didn;t earned so much from my site so that i can buy the paid one so it will help to earn some money from my sute and later i will buy the top hosting provider services after earning decent amount till that time it can help me.

    thanks

    Reply
  46. Hi, thanks for this awesome Giveaway.

    Actually, why i need this free hosting because, till now I don’t own any blog. I have been a content writer in some sites so far. But I’m planning to start my own website and earn from it.

    Also since this is first, I can’t spend much money. And also I don’t know really to create or I mean buy a domain, hosting, cpanel etc etc when other says. So this is my first step toward blogging and looking to get domain and hosting free. Even domain can be got for less 1$, as I saw in some coupon codes in Godaddy. But for hosting many told it would take 6,000rs for 1 year. So only till now I didn’t start.

    So now if I win your hosting, sure I would start a website and start my Blogging career. So please help me and give it. Also it would be nice if you can after if I win, please do guide me in setting up a blog.

    Thank You

    Reply
  47. Pingback: Recursos de la Semana (30/07 - 05/08)

  48. Pingback: How to Get Your Blog on Google Fast

  49. Thank’s admin for this Giveaway, as i m a blogger and i run my blog on blogger.com platform and do very hard work on SEO related, as in blogger there is very difficult to do SEO, so that’s why i want hosting to move my blog to wordpress platform, i know that if i do this much hard work in wordpress then i sure get a good alexa rank & traffic.. this is my main reason to get this giveaway , now just hope for the best

    Reply
  50. Amy rogers – What aminzag talent you have Sarah!! Your pictures capture the personalities of these people so well and they are truly beautiful shots. Great blog, I’m a follower!!

    Reply
  51. I want this hosting because my x10hosting can’t handle my site traffic and bamdwidth
    so i want premium hosting in which i can move

    Reply
  52. Pingback: Advanced Techniques and Tips for Google Search | Design News

  53. Pingback: Impressive FB Covers for Timeline

  54. Thanks DesignSkew.com for arranging such useful giveaway
    I Checked Zyma plan. It is awesome to have all such features free for one year. Looking forward to win this giveaway- praying for the same

    Reply
  55. Pingback: Special London Olympics Pictures 2012

  56. Pingback: My website about Wallpapers and video

      • Love the design, love gaertrs, love women with tattoos. The first reply is very accurate, tattoos will only do what you put them thru. If you get bigger and your skin doesnt stretch out properly (stretch marks, cellutlite, etc.) then yeah it’ll ruin the whole tattoo for good. I should know I got one running up the inside of my upper arm and then I got bigger and didnt take care of my skin as I did get bigger and now the whole tattoo is ruined by the stretch marks I got. The tattoo can be redone, but only when I get to a smaller size to make it all even and complete again. Getting a tattoo in my opinion means that you are going to take care of it for the rest of your life, meaning staying in shape to keep it looking good, putting sunscreen on it to protect it, not going near salt water for like 6 months after getting one, etc. Be good to the tattoo and the area its on and it’ll always be good to you.

        Reply
  57. Pingback: My website about Wallpapers and video

  58. I’m truly enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and
    visit more often. Did you hire out a developer to create your
    theme? Excellent work!

    Reply
  59. Pingback: 10 Basic Photoshop Coloring Tutorials[Video Tutorials]

  60. Pingback: The New iPhone 5 Concept Designs and Looks

  61. but how to embed these in wordpress.,
    here is only demos/downloads links., no plugin for wordpress ??
    how to make it possible to use in wp ??

    Reply
  62. Pingback: iPhone 5 Retina Wallpaper | KlonBlog

  63. Pingback: How to Secure Your Account from Online Facebook Hacking

  64. Pingback: 20 HD iPhone 5 Retina Wallpapers | DotMac

  65. Pingback: Impressive FB Covers for Timeline | 99Covers Blog

  66. Pingback: How to Secure Your Account from Online Facebook Hacking

  67. Pingback: Awesome, Best and Cool Facebook Timeline Covers | 99Covers Blog

  68. Pingback: Best iPhone 5 Cases

  69. Pingback: 3 Funny Flash Animations

  70. Pingback: 3 Funny Flash Animations

    • Hi,

      I have a wordpress.org installation and in the header.php i don’t see any tags.

      How do i activate google analytics in such a case.

      Reply
  71. Pingback: Better Camera Replacement Android App

  72. Pingback: HD Galaxy Nexus Wallpapers and Backgrounds

  73. Echo is faster than print by one opcode so it really don’t matter, really. And print() is a function, echo is not. Try this:

    $variable and print ‘variable is set!’;

    And about incrementing: $i += 1; is the fastest one.

    Great article, thanks!

    Reply
  74. Pingback: 10 Amazing HD Gaming Wallpapers You Would Love

  75. Pingback: 5 Cool jQuery Demos and Examples

  76. Pingback: 50 High Quality And Inspiring HD Desktop 3D Wallpapers

  77. Pingback: Thesis Statement Skin for Thesis 2.0 Theme

  78. Pingback: How Derek Halpern Helped me focus on Readers and not Visitors

  79. Informative and useful post! Well yes, getting Google authorship gets high CTR for search results and also Google’s trust as a good author. Thanks for sharing :)

    Reply
  80. Pingback: Download HTML5 and CSS3 Website Admin PSD Template

  81. Pingback: 50 Scary Halloween Desktop Wallpapers

  82. Pingback: 50 Scary Halloween Desktop Wallpapers

  83. Pingback: 50 Scary Halloween Desktop Wallpapers | Accounting and Small Business /Beverly Shares

    • Thanks for the mention. As I said, there are lots of tools online to perform any specific operation on Twitter. Though, thanks for reading and for being a valuable reader.

      Reply
  84. Pingback: 20 Black and White Photography Wallpapers

  85. Pingback: 50 Scary Halloween Wallpapers

  86. Pingback: 30 High Quality And HD Desktop 3D Wallpapers

  87. Pingback: 10 HD Gaming Wallpapers

  88. Pingback: 20 Black and White Photography Wallpapers

  89. Pingback: Twitter Marketing : Tools and Strategies

  90. Pingback: 15 Business Logo Designs

  91. Pingback: 10 New Photoshop Tutorials on Youtube

  92. Pingback: 10 New Photoshop Tutorials on Youtube

  93. Pingback: 10 New Photoshop Tutorials on Youtube

  94. Pingback: 15 Business Logo Designs

  95. Pingback: 10 New Photoshop Tutorials on Youtube

  96. Pingback: 20 Black and White Photography Wallpapers

  97. Pingback: Download HTML5 and CSS3 Website Admin PSD Template

  98. Pingback: 50 Scary Halloween Wallpapers

  99. Pingback: 20 Wildlife Photography Pictures

  100. Pingback: Blogspot vs Wordpress – What is Best Blogging Platform?

  101. Pingback: 20 Retina Wallpapers for iPhone 5

  102. Pingback: 10 Retina Wallpapers for Macbook

  103. Pingback: Beginner’s Guide to Windows 8 App Development

  104. Pingback: 10 New Photoshop Tutorials on Youtube | Design News

  105. Pingback: 20 Creative Photography Ideas Showcase

  106. Pingback: Download Harry Potter Font

  107. Pingback: Thesis Theme 2.0 Giveaway

  108. Pingback: Beginner’s Guide to Windows 8 App Development

  109. Pingback: 30 Minimal and Colorful Web Design Inspiration Examples

  110. Pingback: Creating Paper Note Embossed Text Effect in Photoshop

  111. Pingback: Download Harry Potter Font | Design News

  112. Pingback: Tweet Parade (no.47 Nov 2012) | gonzoblog

  113. Pingback: Beautiful UI Screenshots and Photos

  114. Hey very nice site!! Guy .. Beautiful .. Superb .. I’ll bookmark your web site and take the feeds also?I am happy to find a lot of useful information right here within the publish, we’d like work out more strategies in this regard, thank you for sharing. . . . . .

    Reply
  115. Pingback: A Better Alternative to Google Webfonts | Design News

  116. Pingback: 35 Miley Cyrus New Pictures

  117. Pingback: 20 Funny Pictures for Facebook Timeline

  118. Pingback: 10 Quick Homemade Christmas Gift Ideas for Adult

  119. Pingback: eCommerce Designs | 30 Beautiful Wordpress Examples

  120. Pingback: 10 Christmas Homemade Gift Ideas

  121. Pingback: 10 Ideas for Interior Logo Designs

  122. Pingback: 10 Christmas Homemade Gift Ideas

  123. Pingback: 20 Funny Pictures for Facebook Timeline | DesignSkew

  124. Pingback: Installing Wordpress on Godaddy Hosting | Beginner's Guide

  125. Pingback: 10 Graphic Designers to Follow on Behance Network

  126. Pingback: 50 Artistic Photo Manipulations

  127. Pingback: Nebula 3 Abstract Case for iPhone 5

  128. Pingback: Nebula 3 Abstract Case for iPhone 5

  129. Pingback: 50 Artistic Photo Manipulations | Design News

  130. Pingback: Creative and Inspirational Motion Graphics Video

  131. Pingback: 10 Most Beautiful Artworks

  132. Pingback: 10 Most Beautiful Artworks

  133. Pingback: 10 Most Beautiful Artworks

  134. Pingback: 50 Artistic Photo Manipulations

  135. Pingback: 10 Creative Beautiful Artworks

  136. Pingback: Creative and Inspirational Motion Graphics Video | Design News

  137. Pingback: 3 Extremely Good Typography Examples in Web Design

  138. your blog very helpful for me.keept up. Here we leave a comment for SEO consulting services.
    We at Guru Techno World, SEO consulting services, have a team of expert and dedicated SEO consultant

    who can get our client’s websites in the top positions on all major search engines with proven SEO

    techniques.

    SEO consulting services

    Reply
  139. Pingback: 10 Effective Logo Design Inspiration Examples

  140. Pingback: 5 Creative Business Cards Design

  141. Pingback: Web Development Links Roundup: September 12th | Cool Ryan.com

  142. Yes All right Okay I am also in search look for hunt explore of Photoshop Tutorials on Youtube, because since as I want desire wish for would like to learn more regarding concerning about on the topic, so thus therefore if you have please post it here at this place.

    Reply
  143. Hello very cool website!! Man .. Excellent .. Superb .. I’ll bookmark your web site and take the feeds also? I am glad to seek out so many helpful info here in the post, we want develop extra strategies on this regard, thank you for sharing. . . . . .

    Reply
  144. My coder is trying to persuade me to move to .
    net from PHP. I have always disliked the idea because of the
    expenses. But he’s tryiong none the less. I’ve been using WordPress on a variety of websites for about a year
    and am anxious about switching to another platform.

    I have heard fantastic things about blogengine.net.

    Is there a way I can transfer all my wordpress content into it?
    Any kind of help would be really appreciated!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>