Skip to content
WJunction - Webmaster Forum

10 Ways to improve your PHP

Status
Not open for further replies.
Ok heres a list of ways to improve your PHP Programming..

1. Use the cheat sheets
When ever your programming in php and mysql you should always have a cheet sheet at hand!,

there are several out there for you to use as references here are just some







2. Know your comparison operators


You should make sure you know your comparison operators and should study them wisely, here are some links that will give you information on where to get to know!







3. Short cut the else stament
Speed in programming is a big thing because you down want your user waiting several seconds for your page to load because as they browse your site the seconds they have waited overall will have a downside to your site.

Take this example of a normal IF / ELSE statement.

PHP:
if( expression ){
$x = 10;
}else{
$x = 5;
}
Now this looks like regular coding but by doing the following will remove the need for the else
PHP:
$x = 5;
if( expression ){
$x = 10;
}
by setting the value of $x before the if statement, when the expression is run if it fails it will just stay at the default value of 5

4. Less {brackets}
When using statements such is the if statement theres no need to have the brackets the command will still execute as normal, this decreases the processing time of the statement and also decreases the size of your script

Example with the brackets
PHP:
if($i == 10){
$i++;
}

Same statement without brackets.
PHP:
if($i == 10) $i++;

You can also use multiple if/else staments using the structure. for example
PHP:
if ($i == 10) $i++; else $i--; 
 
if ($theScene != 'dead') echo 'w00t';
 
foreach ($girls as $girl)
echo 'Heya ' . $girl . ' Fancy a drink?';
This method is used alot within the programming industry but Personally i think it makes your code look less attractive, but if you have the need for speed then use this method.

5. User Ternary Operators
Ternary operators apply to if/else statements and is usually called "Short Hand" its kinda similar to No.4 "Less {Brackets}" act slightly like a function where it will return data into a variable if provided... examples of ternary operators follow.


6. Unset your variables
Unsetting you variabls will free memory in your php allowing other actions to run faster, you unset a variable/array usining the unset() function.. example follows.

PHP:
$myName = 'Litewarez';
 
echo $myname;
 
//Ok so now $myName is not needed throughtout the rest of the script so ill unset it
unset($myname);

Note:
if you have a globalized variable in a function when you unset the variable it will only unset the local instance of that variable.. example below.
PHP:
$myname = 'Litewarez';
 
function myName(){
global $myName;
unset($myName);
}
myName();
echo $myName;

it will still echo Litewarez as only the variable within the function is destroyed but also remember to unset your variables inside functions aswell.

7. Using catching.
on every script you should use catching/buffering to speed up your webstie speed, what catching does is create an internal catch of the current page and compresses it before senduing it to the web-browser.. meaning less data to be sent.

Also i prefer to use ob_start('ob_gzhandler'); instead of ob_start

what the gxhandler does is using gzip to compress the website data if the web-browser accepts gzip-deflate meaning that all web browsers are supported. example below...

PHP:
//you need to call this function before you are going to be outputting data.. such as echo / print / var_dump etc
ob_start('ob_gzhandler');
 
//No we can start doing stuff within outr script
 
if($Litewarez == 'Good Programmer'){
     for($i=0;$i<5;$i++){
          echo 'w00t\n';
     }
}

//now the out put will be compressed and upto 5 times faster :)

8. Using Concatenation.

When you are joinig variables and strings together the method most people use is

PHP:
$User_Welcome = "Hello $user";

No the problem with this is that PHP has to guess the type of operation your trying to perform and this causes slow speeds, by using concatenation php knows what your are trying to gain and then performs the selected task instantly.

Here are some examples of concatenation!

PHP:
<?php 
 
$Welcome_Start = 'Welcome';
$Username = 'Litewarez';
$Welcome_End = 'to your profile';
 
/*
This is the WRONG way to join them strings together!!!!
*/
 
$Welcome = "$Welcome_Start $Username $Welcome_End";
//OUTPUT: Welcome Litewarez to your profile
 
/*
This is the CORRECT way
*/
 
$Welcome =  $Welcome_Start.' '.$Username.' '.$Welcome_End;
//OUTPUT: Welcome Litewarez to your profile
?>

all you need to know is joining a variable with a string ( "string" . $var ) is faster


9. Using Incremental Operators.
Now these are some operators that are widely used when dealing with numbers, but im going to show you the importance of POST / PRE incremental operators.

heres the 4 variations of these types of mathematical operators

  • Increment
    • $number++
    • ++$number
  • Decrement
    • $number--
    • --$number
the difference is that the POST (++ or --) comes after the variable and the PRE (++ or --) comes before.

the reason for this is the fact that if you use the POST method then the nuber will be incremented AFTER it has been return and if you use PRE method then the number will be incremented then return.. some examples below

PHP:
<?php 
$number = 5;
 
//POST
echo 'I should be 5 : '.$number. '<br />';
echo 'I should be 5 : '.$number++. '<br />'; // here iv'e started to increment it
echo 'I should be 6 : '.$number. '<br />';
echo 'I should be 6 : '.$number--. '<br />';
echo 'I should be 5 : '.$number--. '<br />';
 
echo '<br />';
$number = 5;
//PRE
echo 'I should be 5 : '.$number. '<br />';
echo 'I should be 6 : '.++$number. '<br />';
echo 'I should be 7 : '.++$number. '<br />';
echo 'I should be 6 : '.--$number. '<br />';
echo 'I should be 6 : '.$number. '<br />';
?>

now as you can see that when using the ++ before the variable the maths is instance so to speak but when you are using ++ after the variable the changes will not be see until the next time the variable is called.

10. Error Supressions

Ok we NEED to know about error supression when using functions.



if you have built a website and everything is going well and then you start seing an error on your site, well you dont want users to see this error because:
  1. Looks Nasty
  2. Messes up your design
  3. * helps hackers gain information about your directory structure
Now we dont want any of that now do we? so im going to show you how to supress errors when your programming.

Theres a few ways you can do this:
In your php.ini file you can take control of the error_repoerting settings and turn of all errors on your website

this is what the settings look like in your php.ini file and you can change these accordingly!

Code:
error_reporting = E_ALL & E_NOTICE & E_STRICT



Possible Variations.
  • E_ERROR => 'error'
    E_WARNING => 'warning'
    E_PARSE => 'parsing error'
    E_NOTICE => 'notice'
    E_CORE_ERROR => 'core error'
    E_CORE_WARNING => 'core warning'
    E_COMPILE_ERROR => 'compile error'
    E_COMPILE_WARNING => 'compile warning'
    E_USER_ERROR => 'user error'
    E_USER_WARNING => 'user warning'
    E_USER_NOTICE => 'user notice'
Now you can read up about these error constants by reading here
http://uk3.php.net/manual/en/function.error-reporting.php

Also the necxt way to change the error types is by using a function in you php script calle error_reporting().

heres an example of the usage

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);


and the next way to do this is by adding the supresser to your functions witch will be the at symbol (@) before the Function so heres an example

PHP:
//Working Function
$data = @file_get_contents('http://www.somesite.com');
 
//Function that will cause an error
 
$data = @file_get_contents(1,4,'hello',helloooo);

oki so without the @ sysbols the second function will; have couse your script to stop executing with an invlaid parameters error

so just take into mind that its best to set your php.ini other than using the at sysbol becuase if your debugging you site you dont want to go threw your script removing the @ sysbol from everywhere..

11. End-Credits

theres not really much to put in here apart from i hope you enjoy learning some PHP and comment like mad if you like.

My name: Litewarez, aka Cornetofreak

NOTE: yuou may copy this post from http:www.wjunction.com/ and post it where ever you feel like but please give credits to the original contributer.

​
 

20 comments

its not a myth im pretty sure that php processes while / if statments without the braces before trying to parse with the braces so in thoery your right it would not make a huge difference unless you had a large script but consider the amount of if staments that are carried out within a website INCLUDING the ones in loops and then it should make a visible difference to the benchmark reasults..
 
Nice tips but #4 is a mytth. Unless you make yourself a 10MB PHP file it won't matter.

yep - i have a 200,000 line php project im writing - i get exec times on a VM of less than 0.001 seconds. i think the most important ones to use are Output buffer and unset.

they make a huge difference
 
lets say you had 200 variables set at 1kb each, that means the variables are holding 200K+ of memory.. by using unset throughout your script you can always free the memory thus cousin more memory to handle other tasks
 
litewarez... its way more than 200 variables... the search engine has huge arrays for "humanising" the search results... it uses 12SQL queries for a each search building up a profile of your searching and adapting to it... a bit like google.
 
Alot of people just need to learn the simple php optimisations like

'test'.$test
instead of
"test $test"

and $test['index'] instead of $test[index]

Annoys me sooo much when I have to clean up their code before I use it in my projects.
 
yea concatenation make your code look more cleaner

the reason for this is that by doing "Hello $user"... PHP has to guess what you want to achieve but when you are using predifined actions such as the concatenation dot PHP knows what your are trying to do thus making it faster!

and is faster also using ' ' when assigning an array increases your speed alot due to the fact that php don't have to guess weather its a string / bool / integer etc
 
Thanks litewarez was a good read, maybe mention the functions file_get_contents and file_put_contents they save a lot of unneeded lines when dealing with files :P
 
If people are concerned more about speed, they should not use OOP as well. #4 makes your code look clean, and so does OOP.
 
Status
Not open for further replies.

About the author

L
Active Member · Joined
I am a skilled programmer within PHP,HTML,CSS,MYSQL and also the owner of several websites Programming, Football...
1,367
Messages
1
Reactions
38
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom