13 Jan 2013

PHP #1: Output Data to the Page

echo and print

In order to display data to the screen, you need to use one of two language constructs, either echo or print. To all intents and purposes, they're the same - use whichever you prefer the look of - I tend to use echo.

<?php  
    echo "Hello World!";  
?>  

Alternatively use print:

<?php  
    print "Hello World!";  
?>  

You should find that you get identical outputs:

Hello World!

There are other ways to output data to the screen, including print_r() and var_dump(). However, these tend to be used for checking internal data, such as variables.

Escaping Characters

As pHp requires either single quotes or double quotes around string (text) data in order to display it to the screen, text containing quotes can be problematic, as they can break the code, for example:

<?php  
   echo "They all shouted "Help!", in unison";  
?>  

This would result in an error, such as:

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in C:\xampp\htdocs\mysite\index.php on line 2

In much the same way, the following snippet, would also raise the same error:

<?php  
    echo 'Don't ever call me that!';  
?>  

Notice that single quotes and apostrophes tend to be the same character. For this reason alone, coders often tend to use double quotes for static text. There is no problem with enclosing double quotes within single quotes and vice-versa. So, the following are fine:

<?php  
    echo 'They all shouted "Help!", in unison';  
    echo "Don't ever call me that!";  
?>  

OK, so far, so good, but what if some text contains both single quotes/apostrophes and double quotes? Well, in this case we need to escape the offending characters. This is done simply be placing a backslash character in front of the character. Escaping all quotes - just in case - is safe to do, as the backslash character is not displayed on the screen. So each of the following will display the text as intended:

<?php  
    echo 'They all shouted "Help!", in unison. Don\'t ever call me that!';  
    echo "They all shouted \"Help!\", in unison. Don't ever call me that!";  
    echo 'They all shouted \"Help!\", in unison. Don\'t ever call me that!';  
    echo "They all shouted \"Help!\", in unison. Don\'t ever call me that!";  
?>  

So Which is the Best to Use?

You may read many things about the evils of complicated concatenation or the added time required to parse variables, etc, etc, yawn, yawn. Forget it, it doesn't really matter, to me, it's a question of convenience. It can however depend on the context of what you're outputting - if you want to output variables, or not.

<?php  
    $num_pigs = 10;  
    echo "I have $num_pigs pigs on my farm.";  
?>  

The snippet above will display the following:

I have 10 pigs on my farm.

<?php  
    $num_pigs = 10;  
    echo 'All $num_pigs pigs squeal in unison';  
?>  

The snippet above will display the following:

All $num_pigs pigs squeal in unison.

Notice that single quotes take variable names literally.

So how do we display variables within our text using single quotes? Well, we fall back on concatenation. This simply means 'join-up this bit and the next bit' and we use the dot operator (.):

<?php  
    $num_hairs = 3;  
    echo 'I have ' . $num_hairs . ' hairs on the top of my head.';  
?>  

This will give:

I have 3 hairs on the top of my head.

Concatenation isn't the sole preserve of the single quoted text, you can use it with all sorts of bits and bobs:

<?php  
    $num_frogs = 100;  
    echo "I have " . $num_frogs . ' bouncing around inside my head.';  
?>  

A Further Example with Double Quotes

Sometimes you'll need to brace out your variables embedded within the text as they may be array variables:

<?php  
    echo "I have {$currency['dollars']}$dollar_cost in my pocket";  
?>  

The braces {...} essentially protect the variable and ensure that it is not affected by following text it can isolate things like array variables. You can only use braces within double quotes. For an actual explanation of braces, see the php manual, as it is too lengthy to include in this beginner's tutorial.

Heredoc and Nowdoc Syntax

pHp is very flexible as it allows you to mix php code and html. This however is also a weakness as it can lead to very untidy code, which is difficult to maintain. There are instances however, when this is just too convenient to ignore. Enter the Heredoc and Nowdoc Syntaxes (BTW - what is the plural of syntax??).

The heredoc syntax behaves just like double quoted text, but without the quotes themselves. In order to set up heredoc text, you need to set an identifier. This can be pretty much anything you want, but it must be in the following format - with the closing identifier in the first column in the last line - no spaces or anything - before it. The following example has DIAFOL as the identifier.

<?php  
echo <<<DIAFOL
    This is probably the worst game of rugby I've ever seen in my life.
    Could you imagine anything worse than Wales losing to Brynaman U11's?
    It was "shocking". The score was $brynaman_score : $wales_score
DIAFOL;
?>  

The code above would output the following, assuming $brynaman_score was 100 and $wales_score was 0:

This is probably the worst game of rugby I've ever seen in my life. Could you imagine anything worse than Wales losing to Brynaman U11's? It was "shocking". The score was 100 : 0

You'll notice a couple of things:

  1. You don't need to worry about escaping double or single quotes. Yipee!
  2. Line breaks within the heredoc syntax are not respected - not even \n characters. Boo!

In order to maintain line breaks, you'll need to introduce <br /> tags or just use <p> tags. Remember this will just spit out html or plain text. So, to maintain line breaks:

<?php  
echo <<<DIAFOL
    This is probably the worst game of rugby I've ever seen in my life.<br />
    Could you imagine anything worse than Wales losing to Brynaman U11's?<br />
    It was "shocking". The score was $brynaman_score : $wales_score
DIAFOL;
?>  

Or even:

<?php  
echo <<<DIAFOL
    <p>This is probably the worst game of rugby I've ever seen in my life.</p>
    <p>Could you imagine anything worse than Wales losing to Brynaman U11's?</p>
    <p>It was "shocking". The score was $brynaman_score : $wales_score</p>
DIAFOL;
?>  

The nowdoc syntax is to single quoted text as the heredoc syntax is to double quoted text. The only difference here is that we use single quotes to enclose the open identifier:

<?php  
echo <<<'DIAFOL'
    This is probably the worst game of rugby I've ever seen in my life.
    Could you imagine anything worse than Wales losing to Brynaman U11's?
    It was "shocking". The score was $brynaman_score : $wales_score
DIAFOL;
?>  

This will output the following:

This is probably the worst game of rugby I've ever seen in my life. Could you imagine anything worse than Wales losing to Brynaman U11's? It was "shocking". The score was $brynaman_score : $wales_score

You'll notice a couple of things again:

  1. Just like heredoc - no need to escape quotes and line breaks not respected.
  2. Variables are literal.

You may be wondering just how useful that is - and to be honest, for day to day stuff, probably not very. However, if you're writing an article or trying to explain the workings of some code or other, having nowdoc NOT try to parse your variables is quite handy. To achieve the same thing in heredoc, you need to escape the $ symbol of variables:

<?php  
echo <<<DIAFOL
    This is probably the worst game of rugby I've ever seen in my life.
    Could you imagine anything worse than Wales losing to Brynaman U11's?
    It was "shocking". The score was \$brynaman_score : \$wales_score
DIAFOL;
?>  

OK, that's the end of this first tute on pHp. I hope it was useful - if it was, stroke my ego and leave some love - else - leave a comment anyway and tell me where I went wrong.

No comments:

Post a Comment