• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Strings / Creating Strings in PHP

Creating Strings in PHP

14 September 2009 / 2 Comments

A string in PHP is any sequence of characters. Here are some examples of strings:

  • Hello, world!
  • abc123
  • #@@$%&*%

PHP lets you work with strings in many different ways. For example, you can search a string for a piece of text; extract characters from a string; and format a string to make it easier to read or use.

In this tutorial you learn how to create strings in your PHP scripts. You look at:

  • Creating strings with single quotes and double quotes
  • Avoiding confusion by using braces syntax
  • Escape sequences
  • How to create multi-line strings
  • Using your own delimiters to create strings

Creating strings using single and double quotes

To include a literal string in your PHP script, simply enclose the string in:

  • Single quotes — e.g. 'Hello there!', or
  • Double quotes — e.g. "Hello there!".

If you use single quotes then PHP reads the string exactly as you typed it. Double quotes work in a similar way, but a couple of extra features also come into play:

  • Variable parsing: Variable names within the string are replaced with the corresponding variable values
  • Character escaping: You can use escape sequences to include special characters in the string

Variable parsing in double-quoted strings

Here’s an example that shows variable parsing in action:


$myString = 'there'; 
echo 'Hello, $myString!<br/>'; // Displays "Hello $myString!" 
echo "Hello, $myString!<br/>"; // Displays "Hello there!" 

Notice how, with single quotes, the "$myString" text is interpreted as-is, while with double quotes, "$myString" is replaced with the contents of the $myString variable ("there").

Sometimes you run into problems with variable parsing — for example:


$favouriteBird = 'owl'; 
echo "My favourite birds are $favouriteBirds"; // Displays "My favourite birds are " 

Here you want to insert the value of the $favouriteBird variable, but PHP thinks you mean the $favouriteBirds variable (which doesn’t exist). The solution is to wrap the variable name (and, optionally, the dollar sign) in curly braces:


$favouriteBird = 'owl';
echo "My favourite birds are $favouriteBirds"; // Displays "My favourite birds are " 
echo "My favourite birds are ${favouriteBird}s"; // Displays "My favourite birds are owls" 
echo "My favourite birds are {$favouriteBird}s"; // Displays "My favourite birds are owls" 

Curly braces also let you include more complex expressions in strings, such as array elements and object properties:


echo "My name is {$myDetails['name']}.";
echo "My name is {$me->name}.";

Character escaping in double-quoted strings

Here’s an example that demonstrates character escaping:


echo '<pre>Hitthere!</pre>'; // Displays "Hitthere!"  
echo "<pre>Hitthere!</pre>"; // Displays "Hi      there!" 

With single quotes the t text is used as-is. However, with double quotes, the t is recognized as the escape sequence for a tab character, so a tab is inserted into the string.

As well as the “tab” escape sequence (t) just shown, there are many more escape sequences you can use in double-quoted strings. Here are a few common ones:

n
Line feed (ASCII 10)
r
Carriage return (ASCII 13)
t
Horizontal tab (ASCII 9)
v
Vertical tab (ASCII 11)
f
Form feed (ASCII 12)
\
Literal backslash
$
Literal $ (dollar) symbol
"
Literal double quote

Example:


echo "Here's a double quote: "";

Result:


Here's a double quote: "
Use ' to include a literal single quote inside a single-quoted string. To include the literal 2-character sequence ', use \'.

Creating multi-line strings

If you want to insert a multi-line string in your PHP code, just use newlines to end each line:


$myString = "Line 1nLine 2nLine 3n";

$myString = " 
  In himself he is;
  But in this kind, wanting your father's voice,
  The other must be held the worthier.
";  

Using your own delimiters: heredoc and nowdoc

You can also surround a string with your own delimiters by using PHP’s heredoc syntax:


$myString = <<<MY_DELIMITER
  In himself he is;
  But in this kind, wanting your father's voice,
  The other must be held the worthier.
MY_DELIMITER;

Heredoc syntax is handy if your string contains a mixture of single and double quotes, since it saves you having to escape them:


$myString = <<<MY_DELIMITER
'Then she said "goodbye" and
left,' he continued.
MY_DELIMITER;

Heredoc syntax behaves like double-quoting — variables in the string are parsed and escape sequences are processed. If you want to avoid this, use nowdoc syntax, which is the equivalent of using single quotes. Nowdoc syntax is the same as heredoc syntax, except that you enclose the first delimiter in single quotes:


$myString = 'there';

$heredocString = <<<END_TEXT
Hello, $myString!<br/>
END_TEXT;

$nowdocString = <<<'END_TEXT'
Hello, $myString!<br/>
END_TEXT;

echo $heredocString; // Displays "Hello, there!"
echo $nowdocString;  // Displays "Hello, $myString!"

You now know how to create PHP strings. You’ve seen how to use single and double quotes to insert string literals in your PHP scripts; how variable parsing and character escaping work; how to create multi-line strings; and how to use your own string delimiters with heredoc and nowdoc syntax. Happy coding!

Filed Under: PHP Strings Tagged With: braces, character escaping, double quotes, escape sequences, heredoc, multi-line strings, nowdoc, php string literals, php strings, single quotes, variable parsing

Reader Interactions

Comments

  1. Paul Collins says

    9 August 2020 at 7:50 pm

    Dear Matt:
    Thanks for your article, but this article and other (articles & websites) have left me puzzled as how to output the following string in PHP.

    What I need/want (desired output from concatenating several strings – have tried different ways in PHP):
    first last

    What I get (no matter how/what method I try) (I’ve tried numerous methods):
    first last

    Here’s what I get if I replace

    so by the process of elimination, the character < is truncating building of the output string.
    I've tried building a string of the above using .= and then concatenating that string with the bigger string, but the only way that I get anything past abc def is to replace the < with some other character.
    How do I get what I need in PHP?
    I know there has to be a way to do this, but no search string I've entered has helped me find it.
    Help!
    Thanks

    Example:

    $msg = 
    "Your Name: " . $your_name . "<BR>" .
    "Your Email Address: " . $your_email_address . "<BR>" . 
    "Your City, State/Province & Country: " . $your_city_stateprovince_country . "<BR>" .
    "<BR>" .
    "Your Dance Request(s): " . $your_dance_requests . "<BR>" .
    "<BR>" .
    "Your Dance Teaching Request(s): " . $your_dance_teaching_requests . "<BR>" .
    "<BR>" .
    "Your Questions, Comments, Feedback: " . $your_questions_comments_feedback . "<BR>" .
    "<BR>" .
    "Your Composite Email: " . $your_name . ' <' . $your_email_address . '>' . "<BR>";
    "<BR>" ;
    
    Reply
  2. Paul Collins says

    9 August 2020 at 9:10 pm

    Dear Matt:
    I knew there was an answer and because I am stubborn, I finally found it.
    However it was not easily found because the description of how to do this was not written in what I would call “Plain, Understandable English”.
    I found a rather oblique description in
    https://www.w3schools.com/php/func_string_htmlspecialchars.asp
    I used the code: ” <” to replace ” <" and that worked.
    Sincerely,
    Paul

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits