Monday, June 29, 2009

Echo vs Output buffer

Here I am again. Lately i've been working on my framework - Samstyle PHP Framework - and now i am here to share with you about Echo versus Output Buffering.

Just today I have tested and proved why output buffering then echo is always better than a direct echo. For this, i created a script that will first run:

$u = 10000;
while($u-- > 0){echo 'testing 123<br/>';}

then next run the following:

$u = 10000;
$b = '';
while($u-- > 0){$b.= 'testing 123<br/>';}
echo $b;

(Psst for reasons why I used a while loop over for loop, look at: )
and then I calculated time taken to execute each of the code.

I found that buffering the output in a variable first (in this case $b) then output, is much faster compared to direct output.

For the first run, it took 0.183017015457 seconds. As for the second run, it took 0.0580809116364 seconds. That's an amazing speed improvement of more than 1/3 of the original code.

Even running only 100 times instead of 10000 times, there's still a significant difference between the speed of the 2 runs. Try that now!

Note that the timings taken are an average of 5 runs spreaded across 5 mins (i.e. 1 run per minute) for the most accurate timings. Please note that the timings may differ from computer to computer. I am using Intel QuadCore 2.4GHz, 4GB RAM, Windows XP SP3, XAMPP 1.7.1, PHP 5.2.9.

Tuesday, June 23, 2009

Image Comparison Tool

Remember the Image Comparison script i had mentioned earlier on? I have compiled it into a Windows console application.

Download the free Image Comparison Tool:

Usage: imgcmp image1.ext image2.ext

Cheers to all! It will return in percentage as output on the console.

Sunday, June 21, 2009

PHP GD: Getting pixel information

Hello there! It's Sam Yong here again. Earlier on I was developing a PHP script for comparing 2 images and find out their similarity. I was rather successful with it.

Well, today I am going to discuss about PHP's GD library - how to get the Red, Green, Blue information of a pixel of an image resource.

Firstly, when we want to get a pixel's color information from an image, we use imagecolorat. The function returns a 24 bit RGB information in Integer. So by shifting the bits, you will be able to get the individual Red, Green, Blue components of the RGB information in integer.


// retrieve rgb info from $img resource at ($x,$y)
$rgb = imagecolorat($img,$x,$y);

$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;


Note that each color has a value that runs from 0 to 255 (8 bit).

Friday, June 19, 2009

Variable Variables

Have you really thought about how dynamic PHP can be? Well seriously if you haven't, check this out! Variable variables.


$a = 'hello';
$hello = 'hello world!';
echo $$a;

// outputs as "hello world!"


Why? $$a is evaluated automatically by PHP into $hello, since $a is 'hello'.