Awesome Tips and Tricks for PHP Beginners

Posted in Tutorials • Posted on 29 Comments

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']).

7 Written ArticlesWebsite

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.

29 Comments Best Comments First
  • Mia Lazar

    Wednesday, October 13th, 2010 14:29

    4

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

    +1
    • Brad Billman

      Wednesday, October 13th, 2010 22:48

      7

      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.

      +1
  • Brad Billman

    Wednesday, October 13th, 2010 21:09

    5

    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.

    +1
  • MaD man

    Friday, February 18th, 2011 11:53

    28

    ThaNx For Tutorails MaN

    +1
  • Matt

    Thursday, October 14th, 2010 16:09

    14

    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 :)

    0
    • Brad Billman

      Friday, October 15th, 2010 17:13

      20

      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.

      0
  • djavupixel

    Thursday, October 14th, 2010 12:12

    12

    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?

    0
    • Brad Billman

      Friday, October 15th, 2010 17:17

      22

      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!

      0
  • Justin Kimbrell

    Thursday, October 14th, 2010 13:58

    13

    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.

    0
    • Brad Billman

      Friday, October 15th, 2010 17:14

      21

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

      0
  • mario

    Thursday, October 14th, 2010 01:30

    9

    Oh well, the single quote myth. No PHP beginners guide is complete without it.

    0
  • Tanel

    Wednesday, October 13th, 2010 15:32

    2

    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…

    0
    • Tanel

      Thursday, October 14th, 2010 10:30

      15

      It seems it is not possible to write php into comments. here’s a link where the aleternative syntaks is described in detail. it works great inside html script.

      http://php.net/manual/en/control-structures.alternative-syntax.php

      0
    • Brad Billman

      Wednesday, October 13th, 2010 22:46

      6

      Rasmus Lerdorf (the creator of PHP) uses short tags. But if you are programming on servers that you have no access to and know nothing about then yes you should not use short tags. But they have decided to keep short tags despite the stories about them being removed from PHP6. So in reality the majority of the time short tags are great.

      0
    • Tanel

      Thursday, October 14th, 2010 10:19

      11

      <!–

      –>

      0
  • Francois

    Wednesday, October 13th, 2010 18:26

    3

    Nice article and nice tips ! More of this.

    0
    • Brad Billman

      Wednesday, October 13th, 2010 22:51

      8

      Much thanks. I do work on request if you have anything you would like to see.

      0
  • Olivier B

    Wednesday, October 13th, 2010 14:54

    1

    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

    0
  • George Birbilis

    Thursday, October 14th, 2010 16:33

    16

    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

    0
  • farid

    Friday, October 15th, 2010 17:42

    24

    very effective for beginner learner

    0
  • Shrikrishna Meena

    Monday, October 25th, 2010 16:45

    25

    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.

    0
  • Big6b

    Saturday, November 13th, 2010 07:06

    26

    I like the concept of short tags for inline if Its quite useful for beginners like me in php

    0
  • Sonu

    Thursday, April 19th, 2012 11:06

    29

    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…

    0
  • Brett Widmann

    Tuesday, January 25th, 2011 05:11

    27

    These are really helpful tips! Thank you.

    0
  • Eric

    Friday, October 15th, 2010 03:26

    18

    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!

    0
  • Ozan Dikerler

    Thursday, October 14th, 2010 10:54

    17

    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

    0
    • Brad Billman

      Friday, October 15th, 2010 17:18

      23

      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.

      0
  • kulit

    Friday, October 15th, 2010 15:15

    19

    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?

    0
  • Oliver

    Thursday, October 14th, 2010 03:09

    10

    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; ?>

    -1
  • Sonu

    Thursday, April 19th, 2012 11:06

    29

    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…

    0
  • MaD man

    Friday, February 18th, 2011 11:53

    28

    ThaNx For Tutorails MaN

    +1
  • Brett Widmann

    Tuesday, January 25th, 2011 05:11

    27

    These are really helpful tips! Thank you.

    0
  • Big6b

    Saturday, November 13th, 2010 07:06

    26

    I like the concept of short tags for inline if Its quite useful for beginners like me in php

    0
  • Shrikrishna Meena

    Monday, October 25th, 2010 16:45

    25

    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.

    0
  • farid

    Friday, October 15th, 2010 17:42

    24

    very effective for beginner learner

    0
  • kulit

    Friday, October 15th, 2010 15:15

    19

    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?

    0
  • Eric

    Friday, October 15th, 2010 03:26

    18

    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!

    0
  • Ozan Dikerler

    Thursday, October 14th, 2010 10:54

    17

    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

    0
    • Brad Billman

      Friday, October 15th, 2010 17:18

      23

      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.

      0
  • George Birbilis

    Thursday, October 14th, 2010 16:33

    16

    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

    0
  • Matt

    Thursday, October 14th, 2010 16:09

    14

    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 :)

    0
    • Brad Billman

      Friday, October 15th, 2010 17:13

      20

      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.

      0
  • Justin Kimbrell

    Thursday, October 14th, 2010 13:58

    13

    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.

    0
    • Brad Billman

      Friday, October 15th, 2010 17:14

      21

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

      0
  • djavupixel

    Thursday, October 14th, 2010 12:12

    12

    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?

    0
    • Brad Billman

      Friday, October 15th, 2010 17:17

      22

      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!

      0
  • Oliver

    Thursday, October 14th, 2010 03:09

    10

    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; ?>

    -1
  • mario

    Thursday, October 14th, 2010 01:30

    9

    Oh well, the single quote myth. No PHP beginners guide is complete without it.

    0
  • Brad Billman

    Wednesday, October 13th, 2010 21:09

    5

    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.

    +1
  • Mia Lazar

    Wednesday, October 13th, 2010 14:29

    4

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

    +1
    • Brad Billman

      Wednesday, October 13th, 2010 22:48

      7

      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.

      +1
  • Francois

    Wednesday, October 13th, 2010 18:26

    3

    Nice article and nice tips ! More of this.

    0
    • Brad Billman

      Wednesday, October 13th, 2010 22:51

      8

      Much thanks. I do work on request if you have anything you would like to see.

      0
  • Tanel

    Wednesday, October 13th, 2010 15:32

    2

    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…

    0
    • Brad Billman

      Wednesday, October 13th, 2010 22:46

      6

      Rasmus Lerdorf (the creator of PHP) uses short tags. But if you are programming on servers that you have no access to and know nothing about then yes you should not use short tags. But they have decided to keep short tags despite the stories about them being removed from PHP6. So in reality the majority of the time short tags are great.

      0
    • Tanel

      Thursday, October 14th, 2010 10:19

      11

      <!–

      –>

      0
    • Tanel

      Thursday, October 14th, 2010 10:30

      15

      It seems it is not possible to write php into comments. here’s a link where the aleternative syntaks is described in detail. it works great inside html script.

      http://php.net/manual/en/control-structures.alternative-syntax.php

      0
  • Olivier B

    Wednesday, October 13th, 2010 14:54

    1

    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

    0

Comments are closed.

23.20.43.165 - unknown - unknown - US