Thursday, July 23, 2009

Using single instead of double quotes in PHP

Today I was reading up on some articles on the web when I suddenly gave thought about the codes I have always been doing.

The other day I was talking to my friend about using single or double quotes, and I persisted on using single quotes instead of double quotes while writing string in PHP. My friend asked why: and here's why we use single quote (') instead of double (").

When writing double (") quotes, PHP parses for variables and control characters (e.g. \n, \r, \t, ...) inside the string:

<?php

$str = "testing";
echo "my string: $str";
// outputs string(18) "my string: testing"

?>


Where possible, use single quotes (') to write strings:

<?php

$str = 'testing';
echo 'my string: '.$str;
// outputs string(18) "my string: testing"

?>


In conclusion: Single quotes speeds things up.

No comments: