PHP: Fun with strings

In the previous post, we talked about creation of variables and output of their values.  Let’s talk a little more about strings.

As we covered, last time, you can store and output values like this:

<?php
    $quoteFromJoe = 'This is something that I said.';
    echo $quoteFromJoe;
?>

Additionally, if you prefer double quotes, you can write the same thing like this:

<?php
    $quoteFromJoe = "This is something that I said.";
    echo $quoteFromJoe;
?>

PHP doesn’t care if you use single quotes or double quotes.  Let’s say, though, that you want the variable to equal I’m not a thief!.

<?php
    $quoteFromJoe = 'I'm not a theif!';
    echo $quoteFromJoe;
?>

The apostrophe in ‘I’m‘ closes the string.  How can you fix that?  One option is to escape the apostrophe.  Another option is to switch to use of double quotes around the value.  So, what if you want to have double quotes around the quote?  You can use both solutions at the same time.

<?php
    $quoteFromJoe = '"I'm not a theif!"';
    echo $quoteFromJoe;
?>

Let’s say that we would like to add attribution to the quote, when we display it.  You can do this

<?php
    $quoteFromJoe = '"I'm not a theif!"';
    echo "$quoteFromJoenn-Joe";
?>

You will notice that I used double quotes around what was being echoed.  If you tried to use single quotes, it wouldn’t work correctly.  You’ll also notice that I used ‘n’ within the string.  What is that?  It acts as a newline character.

So, if there is a special new line character, what others are there?

 

Character Description
 “  Double quote
 n  New line
 r  Carriage return
 t  Tab
 \  Backslash
 $  Dollar sign

 

So, we have covered placing the values of string variables inside of literal strings.  How do you  concatenate variables?  Well, unlike every other language that I’ve seen, the concatenation operator is ‘.‘.  Let’s take a look at an example.

<?php
    $noun = 'Joe';
    $verb = 'is';
    $adjective = 'awesome';
    $punctuation = '!';

    $sentence = $noun . ' ' . $verb . ' ' . $adjective . $punctuation;

    echo $sentence;
?>

The concatenation doesn’t need to happen in the same line, though.  You could also write it like

<?php
    $noun = 'Joe';
    $verb = 'is';
    $adjective = 'awesome';
    $punctuation = '!';

    $sentence = $noun;
    $sentence .= ' ';
    $sentence .= $verb;
    $sentence .= ' ';
    $sentence .= $adjective;
    $sentence .= $punctuation;

    echo $sentence;
?>

 

I have to admit that the period for string concatenation is one of the more annoying things that I’ve seen about this language, so far.

Leave a Reply

Your email address will not be published.