hosted by liquidweb

Go Back   Web Hosting Talk : Web Hosting Main Forums : Web Hosting Talk Tutorials : Programming Tutorials : How To : Improve Your PHP Programming
Closed Thread

Forum Jump

How To : Improve Your PHP Programming

Closed Thread Post New Thread In Programming Tutorials Subscription
Send news tip View All Posts Thread Tools Search this Thread Display Modes
Old 04-05-2006, 04:25 PM
Burhan Burhan is offline
Community Guide
Join Date: Jul 2003
Location: Kuwait
Posts: 5,099
Okay, maybe I should correct some false statements here.

* Commas are apaprently faster than periods when it comes to concatenation
Commas and periods are two very different things. There is only one concatenation operator for PHP, and that is the period (.).

For example, you cannot do this:

PHP Code:
$string 'foo','bar'# !!! Syntax error!! 
I think where the confusion comes in is when people write code like this:

PHP Code:
$string 'foo';
The reason the above code doesn't error out is because echo is a language construct that takes arguments as a comma separated list. Perhaps its more clear with this example:

PHP Code:
echo ($string,'bar'); 
Which is equivalent to the one posted above. So please, don't think PHP has two concatenation operators -- it doesn't. There is only one. Also, goes without saying, one is not faster than the other.

* When using comparison operators, you can either use == or === The latter will check for the type as well as the value and it is faster.
=== is not faster than ==. Please, tell me where you found this out

* switch/case is faster than an if condition
?? How did you figure this one out?

* Type cast any foreach arguments to avoid error messages
This is very bad advice because it will lead to sloppy programming; mainly because PHP won't complain and will turn anything into an array. Instead, use the tools that are provided to you by PHP, namely is_array(). Your example can be better written as:

PHP Code:
$result someFunction();
if (
$result as $foo => $bar)
/* ... */

* If you prepend a function with an AT sign (@), it will not spit out any errors. The same applies to user defined functions.
This is true, but don't use this as an excuse to avoid checking for errors in your code. In my experience, @ creates more problems then it fixes because people don't know how to use it properly.

I haven't had time to read the rest -- but these stood out.

In order to understand recursion, one must first understand recursion.
If you feel like it, you can read my blog
Signal > Noise

Sponsored Links
Old 04-05-2006, 06:04 PM
AdamKDean AdamKDean is offline
Junior Guru
Join Date: Jan 2005
Location: Manchester, UK
Posts: 194
Originally Posted by RACKSET
Or just $rand = rand(3); :-)
Hehe, nope.

Warning: rand() expects exactly 2 parameters, 1 given in /home/imdsm/public_html/dev/test.php on line 3

You must remember that the way rand works, is it takes a value from between "min" and "max":

int rand ( [int min, int max] )

You can view more information about this at

█ Software developer, web designer, and general clever-clogs.
█ C#, XHTML, CSS, PHP, MySQL, MsSQL, T-SQL, Photoshop & more

Old 04-05-2006, 06:09 PM
AdamKDean AdamKDean is offline
Junior Guru
Join Date: Jan 2005
Location: Manchester, UK
Posts: 194
Originally Posted by fyrestrtr
This is true, but don't use this as an excuse to avoid checking for errors in your code. In my experience, @ creates more problems then it fixes because people don't know how to use it properly.
I agree with you on the above, but would like to add that @ is supposed to be used for functions which are liable to error when there isn't a bug. For example mysql_num_rows(), on some older php versions, will error if there weren't any rows selected by a query. This is a great example of how to properly use the @ prefix:

PHP Code:

mysql_query("select * from table");
$numrows = @mysql_num_rows($result);

/* or a better way to do this, would be to use type casting. */

$result mysql_query("select * from table");
$numrows = (int)@mysql_num_rows($result);

/* in this case, if there aren't any rows returned, php wont error but instead return 0 instead of false. */


Hope this is of some use to you.

█ Software developer, web designer, and general clever-clogs.
█ C#, XHTML, CSS, PHP, MySQL, MsSQL, T-SQL, Photoshop & more

Sponsored Links
Old 07-02-2006, 09:39 AM
JeanM JeanM is offline
New Member
Join Date: Apr 2005
Posts: 2
A lot has been said, and a lot has been corrected, there are still some small things I'd like to point out tho...

1. Heredoc
PHP Code:
// Showing a huge chunk of HTML at a time //
<font face="Verdana" color="Orange" size="3">Large, Orange Text in Font Size 3</font>
More HTML down here..
<div align="Center">Centered text</div>
Using the heredoc technique as shown above is best to be avoided. It's a lot slower then going in and out of php tags. The reason for this is that php will ignore parts of the file that are not between php tags and since pure html is of no interrest to php you can skip this and make php parse the page faster.

2. Variables
1. Use variable names that make sense.

a) $string is a string, and $string_array is an array for example. $flag is a flag...
Even better would be to use the following technique to write variables:
PHP Code:
// boolean
$bIsActive FALSE;
$bNeedsRefresh TRUE;

// integer
$iPhoneNumber 042323232;
$iRandNum rand(3,6);

// string
$sErrorMsg 'This is an error';
$sUserName 'JeanM';

// query
$qUserInfo mysql_query("SELECT * FROM user WHERE user = '".$sUserName."'");

// array
$aSmilies = array(':D',':(',':P');
$aUserInfo mysql_fetch_assoc($qUserInfo); 
To sum it up:
1. Use the first letter to tell what kind of variable we are dealing with $un -> $sun
2. Don't use short variables like $sun but instead write full names $sun -> $susername
3. Use a case letter whenever a new word starts, this makes it easier to read: $susername -> $sUserName

This makes coding and using variables A LOT easier and it really isn't more work. Yes you will get longer variables but who cares, what matters most is that you still understand your script 6 months after you first created the script.

3. Quotation
Using Single Quotes VS. Duoble Quotes
some poeple don't know the difference between single and double quotes..
single quotes are faster than double ones because it wont parse variables while the double quotes will look for variables to parse ..
so if you have only hardcoded text, use single quotes but if you have variables use duoble quotes..
PHP Code:
$var 'value';

'this is $var'//prints "this is $var"
echo "this is $var"//prints "this is value" 
While the comment about single quotes being faster than double quotes is true, it is in general good practice to use only single quotes if possible.
PHP Code:
// parsing a string
echo 'using single quotes is faster';

// string with a variable
$sPossible 'possible';
"This would be $sPossible";

$sMuchBetter 'much better';
'But this would be '.$sMuchBetter
Not only does this make php again parse the page faster (it doesn't have to check each character between double quotes to see if there is a variable present) but it's also a lot cleaner for yourself. For example, you no longer have to worry about using double quotes inside double quotes and, when using a proper php editor as noted above, it colors the variables in the correct way, if you had the variables between double quotes it would just parse them in red, as shown above.

One thing to watch out for (which as been stated before in this thread) is that using linebreaks like \n or \r is not possible within single quotes, in this case you could to the following:
PHP Code:
echo "Text with a line break\n" 
But even better would be
PHP Code:
echo 'Text with a line break'."\n" 
3. queries: ` ` vs ' ' vs .. nothing
This is incorrect, INSERT INTO table ($keys) VALUES ($values) ... $keys must be ` ` and $values must be ' '.
example, `id`,`name` .
It is best practice to never use backquotes but instead use column names that are easy to understand and at the same time arent too "general". the reason backquotes are used is to avoid getting an error when for example using the following query:

PHP Code:
mysql_query("SELECT * FROM users ORDER BY order"); 
This will ouput an error because the column name "order" is reserved by mysql (see: Using `` allows you to still use these words, but using backquotes in every query you make is just not feasable, just stick to using column names that have a prefix or use names that you are sure of are not used my mysql.

Last edited by JeanM; 07-02-2006 at 09:43 AM.
Old 07-02-2006, 04:28 PM
innova innova is offline
Web Hosting Master
Join Date: Dec 2002
Posts: 1,300

I agree with what you said, with one exception. The microsoft-like-way of being annoyingly obnoxious with variable names, table names, query names, etc..

$myhouse = 'nice';
$sMyHouse 'nice';

There is no purpose to this whatsoever.

Similarly, in access (offtopic but I think thats where this mess started), you see things like:


Its silly. As if I didnt know tblPerson was a table, or that qFindPeople was a query. I think you should give variables / objects / etc sensible names, but prefixing them with characters that are supposed to show their purpose is meaningless, redundant, and obnoxious for the 'rest of us'.

My other comment on HEREDOC... I love HEREDOC, because I dont have to worry about quotation rules. I just punch out what I want to put in.. I use it a lot for queries - I dont use it to output html / text.

"The only difference between a poor person and a rich person is what they do in their spare time."
"If youth is wasted on the young, then retirement is wasted on the old"

Old 07-02-2006, 05:23 PM
JeanM JeanM is offline
New Member
Join Date: Apr 2005
Posts: 2
I guess it's a matter of preference, but I think that if you work with scripts that include a douzen pages and thousands of lines it's easy to loose track of what variable does what, and with clear naming and stating the type of variable that becomes more clear. For me the capitalized first letters make it easy to read the variables on a page when scanning trough a script that needs to be altered.

Also the heredoc can indeed be used for that purpose, again it's a matter of preference.

Old 08-28-2006, 09:06 AM
Omega-Mark Omega-Mark is offline
Junior Guru
Join Date: Jan 2005
Location: Leeds, England
Posts: 183
i use dreamweaver to code my PHP. it has colour highlighting automatic indentation. and has a built in ftp. i always upload my entire site to a test folder before showing it publicly.

Old 08-28-2006, 08:29 PM
jacobsd jacobsd is offline
New Member
Join Date: Aug 2006
Posts: 3
Very Helpful, Thanks

Old 09-16-2006, 03:08 PM
welshboy welshboy is offline
Join Date: Sep 2006
Posts: 8
thanks for the sweet post, because of this ive realised loads of mistakes in my programming and have sorted them out!! thanks once again

Old 10-13-2006, 11:21 PM
WebGuru72 WebGuru72 is offline
Junior Guru
Join Date: Jan 2006
Posts: 229
very helpful. Thank you all for all the good tips.
One thing I would like to know though..... with sessionstart, how can I have it where it is not in the first thing in the page, I would like to include it in a header but always got errors. any ideas would be great

Web Hosting Review - Real Reviews by Real People Submit your company and get a link to your site, Read Reviews GET YOUR Voice HEARD and REVIEW your HOST NOW!!! Check out our IT Blog Tips & Tricks

Old 10-24-2006, 08:01 PM
CodyRo CodyRo is offline
Web Hosting Master
Join Date: Feb 2006
Location: Buffalo NY
Posts: 1,237
I think you should mention use of variables, don't declare them unless you're going to use it a few times throughout your script.

Also protecting yourself from SQL injections, when / should you cache your work, memcached, etc..

I recommend new coders read these Zend tutorial(s) (There are three parts) for a good primer.

Aside from that nice little writeup, easy to read and informative.

Also I would usually use the following for a include.

PHP Code:
include_once('config.php') or die('Error!');
Keep in mind the difference between include(), include_once(), require_once(), etc.

Cody R. - Chief Technical Officer
Quality Shared and VPS Hosting
Hawk Host Inc. Proudly serving websites since 2004
PHP 5.3.x & PHP 5.4.x & PHP 5.5.X Support!

Old 05-19-2008, 11:46 AM
Padrone Padrone is offline
Join Date: Nov 2007
Location: England
Posts: 8
Very nice, Especially for PHP learners

Old 05-23-2008, 02:24 PM
digitalpioneer digitalpioneer is offline
Temporarily Suspended
Join Date: Feb 2007
Posts: 184
Make sure you optimize your database structure and use indexes. Cache data in memory as much as possible, however this would only be useful if you're website is very inversive with queries. If it is an average site then use a opt cacher, such as XCache. Preform a crap load of benchmarks to help you eliminate most of the bottlenecks. Google can find you a lot of good tips.

Old 05-24-2008, 05:38 PM
Explizite Explizite is offline
Join Date: Dec 2007
Posts: 11
Combining lines is not necessarily a good idea. Some people get annoyed reading scripts containing combined lines.

Old 05-30-2008, 10:45 AM
rjd22 rjd22 is offline
Join Date: Feb 2008
Posts: 5
Programming is all about making your own style. Some people use all the PHP rules others just put something together and don't care. Still nice tutorial for people that just began programming PHP

Closed Thread

Related posts from
Title Type Date Posted
Uhuru Joins Effort to Bring .NET and SQL Server to OpenShift Web Hosting News 2014-03-06 10:33:15
INetU Launches High Performance Cloud Storage Solution Web Hosting News 2013-08-06 13:09:57
Cloudmark Shares Strategies to Avoid Email Blacklisting, Improve Deliverability Blog 2013-05-31 14:57:24
Rackspace Launches Fanatical Support for Developers Web Hosting News 2013-05-16 13:02:32
Oracle Expands Big Data Solutions with DataRaker Acquisition Web Hosting News 2012-12-14 10:46:42

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes
Postbit Selector

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump
Log in with your username and password

Forgot Password?
Web Hosting News:



Welcome to

Create your username to jump into the discussion! is the largest, most influentual web hosting community on the Internet. Join us by filling in the form below.

(4 digit year)

Already a member?