Awesome Tips and Tricks for PHP Beginners

Ok, so now you have “learned” …. wait should that be a single quote …. PHP and you are ready to really be able to start using it for something more than you can do with HTML. I will get into the use of single quotes vs double quotes, short tags, inline if statements, a few other little tips and tricks.

Single Quotes vs Double Quotes

You may ore may not have even thought about this up to this point in your PHP use but it is kind of a big deal. Using the right or wrong quotes can not only cause errors that might be hard to find but there can be a slight performance boost and can make your code much easier to read.

<?php
     echo 'hello world';
?>
<?php
     echo "hello world";
?>

These will produce the exact same end result but do you know which one is technically better? The single quote. The single quote just puts exactly what is inside of it without processing while the double quote actually evaluates and processes. Let me explain with an example.

<?php

      $example = 'hello world';

      echo '$example'; // outcome will be $example

      echo "$example"; // outcome will be hello world
?>

As you can see here the double quotes take the time to process what is inside so technically there will be a little more overhead. Obviously on a small scale this means nothing but if you have a loop that iterates 1000 times you might start to see the benefits of single quotes in a performance sense.

Now if you are trying to put a variable in a sentence you can do this:

<?php

	$example = 'hello world';

	echo 'This is my '.$example.' for PHP';  // outcome This is my hello world for PHP
	echo "This is my $example for PHP";  // outcome This is my hello world for PHP
?>

Either of these will work just the same in getting the output that you want but the single quote will be slightly faster because while both have to process the variable the double quote is also scanning the rest of the sentence in search for anything that it has to process. Yes it is more typing but I personally find the first one much more readable because you can much more clearly see that you are outputing a variable. If this was randomly in a 500 line PHP file the single quote method would be easier to spot.

PHP Short Tags

You know when you just want to prepopulate a form or add one PHP variable into the middle of a an HTML block. Well having to write an open PHP tag and then a close PHP with all of the line breaks and indentions to make it readable is such a pain. So what is the solution? PHP short tags like this.

<?php
	$example = 'This is some text that I want in my paragraph.';
?>
<html>
	<head>
	</head>
	<body>
		<h1>I love short tags</h1>
		<p>
		< ?php
			echo $example;
		?>
		</p>
	</body>
</html>
</pre>
Personally I like to get things done with as little typing and code as possible, so I am not a fan of this.  I love my short tags.
<pre>
<?php
	$example = 'This is some text that I want in my paragraph.';
?>
<html>
	<head>
	</head>
	<body>
		<h1>I love short tags</h1>
		<p>
		< ?=$example?>
		</p>
	</body>
</html>

That will produce the exact same output as the first but much neater and with a little less code.
NOTE: Short tags is something that can be disabled in the php.ini so it is not guaranteed to work but industry standard has short tags enabled.

Short Tags With Inline IF Statement

Short tags are also great when used with inline if statements. Having if statements in an area of the code with a lot of HTML can make it harder to read but using inline if with short tags can make it much neater.

<?php
	$minimum_age = 21;
	$customer = 19;
?>
	<p>You are
	<?php
		if($customer<$minimum_age)
		{
			echo 'NOT';
		}
		else
		{
			echo '';
		}
	?>
	old enough to buy alcohol here.</p>

Obviously we do not need the else in this case because it doesn’t do anything. I just have it in there to help understand inline IF statements. Also since there is only one output line we dont need the curly braces.

<?php
	$minimum_age = 21;
	$customer = 19;
?>
	<p>You are < ?=($customer<$minimum_age?'NOT':'')?> old enough to buy alcohol here.</p>

You see the inline IF is shorter but might be confusing at first so I will break it down.

<ul>
	<li>First "$customer< $minimum_age" is exactly the same as "if($customer<$minimum_age)"</li>
	</li><li>Next "?'NOT':" is the same as "{ echo 'NOT'; }" (anthing after the question mark and before the colon is executed if the statement is true.</li>
	<li>The last piece is the "else" ":''" is the same as "else{ echo ''; }" (anything after the colon is what is executed for the else)</li>
</ul>

And lastly for this post I just want to show a little way to dynamically create variables that can make things a little bit quicker for you. One of the best uses for it is when you are making a database call. Here is a traditional example.

<?php
     $id = '1';
     $query = mysql_query("SELECT name,title,content FROM blog_post WHERE id='$id' LIMIT 1");
     $data = mysql_fetch_assoc($query);
?>
     <div id="blog_wrapper">
          <h2>< ?=stripslashes($data['title'])?></h2>
          <span id="blog_author">< ?=stripslashes($data['name'])?></span>
          <p>< ?=stripslashes($data['content'])?></p>
     </div>

Here we run a query and are outputting the data in HTML format. We do stripslashes() on all of the items because when you insert things into the database it will ad slashes to escape special characters. Instead of having to individually do the stripslashes on everything we can do $$key = stripslashes() like this:

<?php
     $id = '1';
     $query = mysql_query("SELECT name,title,content FROM blog_post WHERE id='$id' LIMIT 1");
     $data = mysql_fetch_assoc($query);
	 if(is_array($data))
	 {
		foreach($data as $key => $value)
			$$key = stripslashes($value);
	 }
     <div id="blog_wrapper">
          <h2>< ?=$title?></h2>
          <span id="blog_author">< ?=$name)?></span>
          <p>< ?=$content)?></p>
     </div>

Now you can see that we can access all of our items from the database like $name,$title,$content. We can do this because the $ in front of $key sets it as a variable with a value of stripslashes($value). Here we are taking the $data array from the query and looping through it. In the foreach($data as $key => $value), $key is the key for that element in the array (which is the reference like $data[‘name’]).

Brad Billman

I am a web developer by trade but originally went to school for Information Technology - Network Engineering Technology at Purdue University. Getting into web development as a student web developer I developed a passion for it that left networking seem a bit boring. Even though I finished up my networking degree I stuck with web development lately I have been a WP7 advocate. My Blog.

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. Sonu says

    Hi,your article is easy to understand but I didn’t get why “LIMIT 1″ are you using? I know PHP Basics but still don’t know much about PHP.One more question if I have article directory script made with PHP & MySql.And on homepage I just want to show only 5 posts.How can I print or show only 5 posts on homepage?

    Waiting for your answer…

  2. Shrikrishna Meena says

    Single quotes and double quotes were really an big deal in php, sometimes just little mistakes resulted into array of long list of errors…..
    But on other side these differences were very useful.

  3. kulit says

    I have a quick question –

    For the last part, how are the variables let’s say “$title” then associated to the data array? As opposed to let’s say, a standard variable name?

  4. Eric says

    I’ve seen some of these short tags in WordPress plugins/themes and elsewhere, but did not understand the syntax until now – thanks for these great tips!

  5. Ozan Dikerler says

    I mostly use this whether it is an array or not;

    while ($data = mysql_fetch_array($query) )
    {
    extract($data);
    echo stripslashes($title); // stripslashes only in required fields
    }

    instead of this;

    $data = mysql_fetch_assoc($query);
    if(is_array($data))
    {
    foreach($data as $key => $value)
    $$key = stripslashes($value);
    }
    echo $title;

    using while() + extract() is a good combination I think

    • Brad Billman says

      It’s funny how long you can programming in a language and still learn something so simple you never came across. I like it and I am guessing it is faster but if you have a lot of variables you still have to do stripslashes a bunch of times and I only use this method on backend so I think there is a place for both probably.

  6. says

    1) I’d expect ZEND’s JIT to convert “…” without any unescaped $ in it to “…” for speed
    2) at 1st example mysql_fetch_assoc the _ isn’t shown at IE8/Vista

  7. Matt says

    If Rasmus jumped off a bridge…….

    Obviously just giving a bit of a hard time, but for a coder to suggest that saving 8 keystrokes is a reason to use a set of tags that may or may not be enabled when migrating projects from host to host seems a little silly imo.

    The problem isn’t so bad, like you said, if you control your hosting environment. BUT, most people do not, and even more, when you go to migrate your code to a new host and it doesn’t work you might know very quickly why it isn’t working. When working with any sort of team though or sharing your code with others, it may not be so obvious to them.

    Well put together article all in all, I’m going to assume you knew there would be some short tags backlash so I’ll just smile and give you a thumbs up :)

    • Brad Billman says

      LOL and thank you. And if you are migrating code there are a lot of things that you will need to watch out for if you have no control. Like someone not having proper permissions on the folder that stores sessions :O… Happened to my company when hosting got switched and of course it was somehow our fault sessions didn’t work for people to checkout.

  8. Justin Kimbrell says

    Good article with some good tips. I have struggled with short tags for a long time, it’s just one of those things that come up again and again. I have decided against them in an effort to make truly modular code.

    The thing this article misses, along with most other beginner articles, is the lack of introduction to OOP (object oriented programming). I wish as a beginner those skills were force fed to me in ever way imaginable. Instead, OOP is considered and advanced technique. Taking it another level is MVC programming. If Model VIew Controller style programming is not talked about in beginner articles. I think MVC programming was the single most important change I made to my skill set.

    I think by not using frameworks (beyond the beginner years) is critical o success. I have seen this time again and again with my own work. Raw php is exactly that, raw. Just like JavaScript and jquery, php frameworks are critical to proffitability ad efficiency.

    • Brad Billman says

      Yeah good point. Perhaps I will get an article together strictly for that. THANKS.

  9. says

    Your code:
    $example = ‘hello world';
    echo ‘This is my ‘.$example.’ for PHP'; // outcome This is my hello world for PHP
    echo “This is my $example for PHP”; // outcome This is my hello world for PHP

    What would you say about that:
    echo ‘This is my ‘,$example,’ for PHP'; // I prefer that! why?

    • Brad Billman says

      You are correct that is faster perhaps I will have to adopt it. Though at a beginner level the performance boost is so low that I think it is better to just keep it simple but thanks for this!

  10. Oliver says

    If you are into performance, use this one:
    echo 'This is my ',$example,' for PHP';

    Why do you use those ugly constructions?
    <?=($customer<$minimum_age?'NOT':'')?>

    This is better and works even short tags are of (standard e. g. on debian systems.
    <?php if($customer<$minimum_age): ?>NOT<?php endif; ?>

  11. Brad Billman says

    The code segment after this line “You see the inline IF is shorter but might be confusing at first so I will break it down.” should not be a code segment. It should actually be an unordered list breaking down all of the aspects of the inline if compared to the standard if.

  12. Mia Lazar says

    Good article but if you choose some of PHP frameworks you can avoid this problems.

    • Brad Billman says

      Frameworks can be very limiting and if you don’t learn PHP before using a framework then you run the risk of missing out on a lot of fundamentals. Personally I do not like PHP frameworks. On the other hand javascript frameworks like Jquery are amazing.

  13. Tanel says

    You should never use short tags as mentioned above there are no guarantees that it will work with every php configuration. One way to make statements and loops goexists with html:

    Var value
    The value of the variable $var is: 1

    same pattern can be used with for, while, foreach etc…

  14. Olivier B says

    Hey great article.
    You ll gonna get some heat on the short tag though. PHP 5.3 disable by default the short tags which for me make sense. One other point which is interesting is the alternative syntax for templates/views.
    is

    hello

    better or

    hello