Diving into PHP: Day 8

Not many people are familiar with “heredocs”. Heredocs allow you to disregard escaping single quotes when typing out long strings. I’ll show you how and when to use them today!

Day 8: Strings

Further Viewing

To learn more about strings, I recommend that you review PHP’s String page.

Download the Source Code



31

Comments
  • Recon says:

    i like your tutorial is well done and you speak very simple for me that are italian
    Thanks Jeffrey

  • Aayush says:

    great one again jeff….

    keep up these awesome screencasts….

  • Vlas says:

    Thanks a lot for the tutorial!!!

  • Brenelz says:

    I would like to let you all know a little gotcha with heredocs that I feel is important.

    For the lines of:
    $myvar = <<<EOT
    EOF;

    You have to make sure that there is no whitespace on these lines.

    For example,
    EOF;

    PHP will throw an error because now it doesn’t know where to end the heredoc. Can be a hair pulling experience as nothing is wrong except that space at the end of that line.

  • Jeffrey says:

    @Brenelz – Yeah – good point. I should have mentioned that.

    Guys – I think you should have a decent understanding of the basics by now. We’ll start moving into some DB work in subsequent video tuts. Should be fun!

  • Gaya says:

    Great screen cast =) cool that you picked up heredocs =D

  • M.A.Yoosuf says:

    yeah its awsome, its new for me, i was wondering when i saw some code in thus way,

    thanks jeff,

    yet you did’t compleate the OOP membershp app, hope soon it will come on NETTUTS

  • Jeffrey says:

    @M.A Yoosuf – Should be soon!

  • hey Jeff if I make screencasts like detailed stuff about html,css,php or whatever just like this, would it be accepted.

  • W.Dohmen says:

    Nice screencast great info on heredocs, didn’t know about it :D , also I thought it is possbile to make a variable work in a string by wrapping it in {}, for example echo ‘Some sentence {$variable} the rest’;? Find it easier when you have just one variable

  • Kevin says:

    You know, I took a 3 month course on PHP + MySQL and never was it mentioned the heredocs feature. Would have saved me some madness testing wise.

    Are there security concerns using this notation for SQL query statements?
    Our teacher suggested we should obfuscate the data items a bit more.

    Thanks for the tutorial, great as always.

    Kevin

  • Jeffrey says:

    Kevin – If you want the easiest way to protect your code against SQL injection, just use prepared statements. We’ll go over that within the next couple of weeks. :)

  • Jeffrey says:

    @Devin – I don’t see why not. You’d need to tell me what you’re tut would be covering first.

  • Brenelz says:

    @W.Dohmen using {} is handy for things like arrays and objects that are more complex variables.

    For example this won’t work:

    $names = array(‘first’=>’john’,'last’=>’doe’);
    echo “hello $names['first]“;

    And this will:
    $names = array(‘first’=>’john’,'last’=>’doe’);
    echo “hello {$names['first]}”;

  • Wuiqed says:

    @W.Dohmen, enclosing a variable between curly braces won’t work in single quotes, only double.

    Also, I prefer to always use single quotes and close them when I need to use variables. Consider the following:
    echo “Echoing a variable is simple.”;
    echo ‘Echoing a variable is simple’;

    The php engine *knows* it won’t need to parse any variables in the second string since it’s in single quotes, but it has to search the double quoted string before it can output anything. Granted, this is minimal processing improvement, but when you scale it up to a whole lot of parsing and a whole lot of visitors, you might see a larger difference.

    So when I need to parse any variables, I do what I’ve done in the second string here:
    echo “Echoing a $myVariable is simple.”;
    echo ‘Echoing a ‘, $myVariable, ‘ is simple’;

  • crypta says:

    I didn’t see Wordpress screencast all week :)

  • Snookerman says:

    Jeff, could you make a page with links to all the PHP tutorials? I have recommended them to many people that want to learn PHP but I can only link to one screencast or the “tutorials” page that has other screencasts as well. Also, they have to click on “older entries” to see the first ones. It would be much better and easier if you had a page called “Diving into PHP” where you put all the links to these tutorials, starting with day 1. If there already is one, could you please direct me in the right way? Thanks a lot for these screencasts!!

  • Roy says:

    Thanks so much for this and the JQuery tutorials!

  • Very nice tutorial. heredocs is an often overlooked feature (to be honest I did not know that was the name of this). This is very handy when outputting HTML chunks because of all the ” and ‘ in the markup.

    $string = <<<EOD

    $title$date

    EOD;

  • LOL the HTML got eaten in my example. Anyway there are a lot of ” in HTML markup. :)

  • Rober says:

    Nothing to do with this but I really want to watch #8 and #9 of jquery for absolute beginners but they seem to be broken.
    Please Jeff, take a look…
    Thanks.

  • Pix says:

    So am i the only one who having problems with this heredocs? I receive an error saying

    PHP Parse error: syntax error, unexpected $end in /Applications/MAMP/htdocs/PHP_exercise/day8/index.php on line 27

    the funny thing is that line 27 is OUTSIDE my php block(it’s the end of the document) and as soon as i start using <<<EOD all my color sintax goes nuts (i’m on a mac with mamp and textmate)

    here is the code that i’m using right now:

    <?php
    $str = <<

    seriously this thing is driving me crazy, what am i missing?

    And for the records i’ve just discovered these screencast today and i’ve watched all of them straight in a row and they are awsome. jeff you have such a relaxing voice :)
    Need MOAR! :)

  • Pix says:

    yeah i was expecting that

    here’s my code

    $str = <<<EOD
    Example of string
    spanning multiple lines
    using heredoc syntax.
    EOD;

    echo $myString;

  • jacob says:

    Thanks Jeff!!
    There is another thing that You could explain – what’s the >practical< difference between values set to NULL, 0, “”, ‘0′ etc..
    In many cases it doesn’t matter that much, but there are some implications based on those values, for example the outcomes of the isset() and array_key_exists() functions.

  • @pix you are setting one var $str but are echoing another $myString.
    Try echo $str;

  • Kathleen says:

    Jeff,

    I’m a newbie to all this and just want to thank you for these tuts. I’m not so terrified of php now. Thanks!

  • Dean says:

    @Brenelz:
    “For the lines of:
    $myvar = <<<EOT
    EOF;

    You have to make sure that there is no whitespace on these lines.”

    The only line you have to watch out for is the EOF; – there can be no whitespace on this line.

    If you indent your code and you have a heredoc inside an if statement, you must make sure that EOF; is not indented.

    Also it’s not possible to use constants inside a heredoc statement which can be a pain sometimes.

    Because I don’t intermix PHP and HTML (except for echoing out variables), I often use heredoc to build large blocks of html and then echo out the variable into the html template.

  • Pix says:

    @Shane Sponagle
    thanks i’ve noticed that,was just a copy-paste error but my problem here is not the echo thing is the whole heredocs block
    i solved thanks to Dean, basically i have to watch the last EOT; and be sure there is NO white space on that line
    thanks!

  • Jason says:

    I am not sure if I understand why using single quotes is faster when it seems like you have to go through more work than just having double quotes take care of it all.

    echo “This is an example using a fake $variable.”;

    as opposed to:

    echo ‘This is an example using a fake’ . $variable . ‘.’

    Can anyone answer that? Does Jeff mean it is slightly quicker because it is just one keystroke instead of two?

    Since I am starting out, I want to figure out the best process so I can form form good habits.

    If anyone knows, please tell.