PHP string concatenation and PHP multiline string command

PHP string concatenation and PHP multiline string command

In this article I will explain about PHP string concatenation, php string types, how to deal with escaping character in PHP, php multiline string command with examples.

String concatenation in php

String concatenation uses period (.) to append one string of character to another.
Examples of string concatenation
1.       $people=3;
                echo “there were ”.$people.” people in car.”;

2.       $manpower .= $no_of_people;

PHP String types

There are two types of string
Single quotation  (‘’) you can use it when you wish to assign a literal string, preserving the exact contents, you must use single quotation mark.
Double quotation (“”) when you want to include variable inside a string you should use double quotated string.

Escaping character

$sentence=’my brother’s name is Mike’; // Erroneous syntax
To correct above statement we can use backslash directly before the offending quotation mark to tell PHP to treat the character literally and not to interpret.
$sentence =’my brother\’s name is Mike’;  //correct statement

$sentence=”my dad says\”love your work\”.”;
Tab=\t
Newline=\n
Carriage return-\r
$work_day=”Date\tName\tPayment”;

PHP Multiline String Command

When you want to output a lot of text from PHP without using several echo (or print) statement, at that time we can use multi line string echo statements of PHP.

<?php
$name=”SEO TO WEBDESIGN”;
echo “This is my first Headline
This is the first line of sentence.
This is second line.
Written by $name.”;
?>

We can also use multiline sequence using <<< operator known as here-document or heredoc for short, is a way of specifying a string literal, preserving line breaks and white spaces in the text.

PHP _END tag for multiline string command

<?php
$name=”SEO To WebDesign”;
echo<<<_END
This is my first line
This is second line.
This is third line.
-written by $name.
_END;

Things to remember

Use _END tags as if it were a double-quoted string.
Closing  _END tag must appear right at the start of a new line and it must be only thing in that line. Not even comment is allowed
You don’t have to add \n infeed  characters to send a linefeed, you just press Return and start a new line.

$name=”PHP Tutorials”;
$output=<<_END
Now I can use many lines.
Between these tags .
This is my third line.
Which is written by $name.
_END;


Share on Google Plus

About Rahul Rana

I am an experienced web designer and SEO expert. I am running my own online marketing company i.e "SEO To Web Design". Thanks for reading, keep sharing online marketing and web design knowledge.
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Enter your email address:

Delivered by FeedBurner