Working with strings in PHP

Working with strings in PHP
5 (100%) 1 vote[s]

In PHP a string is a set of characters, where a character is the same as a byte.

A string can be defined in four different ways:

  • single quoted
  • double quoted
  • heredoc syntax (Behaves like single quoted)
  • nowdoc syntax (Behaves like double quoted)

single quoted string

The simplest way to define a string is to enclose it in single quotes (the character ‘).

To enter a literal single quote, escape it with a backslash (\).
To enter a literal backslash, double it (\\).

$var = 'My first string';
echo $var;
//Result: My first string

Double quoted string

Other way to define a string is to enclose it in double-quotes(“).
If in single quotes, only \\ and \’ had a special meaning, in double quotes, are more escape sequences, like:
\n Line Break
\r Carriage Return
\t Tab Space
\\ Backslash

Carefull!!!

We can use variables inside double quoted strings, because PHP will parse them.

Curly braces syntax

To use a variable with curly braces is very easy. Just wrap the variable with { and } like:

When to use curly braces?

Sometimes, when you are defining a variable inside a string, you have to add characters to variable name, like ‘s’ for plural. So you have to add curly braces to variable, otherwise this will produce an error.

$fruit = 'banana';
echo "I like to eat $fruits";
//Result: Notice: Undefined variable: fruits

Add curly braces to $fruit, like:

$fruit = 'banana';
echo "I like to eat {$fruit}s";
//Result: I like to eat bananas 

Doc Syntax

Doc syntax is used in the following way:

  1. Starts with
  2. add an identifier in the same line enclosed with single quotes(for nowdoc) or double quotes(for heredoc
  3. Write the string in a new line (can be multiline)
  4. Close with the identifier and a ; in a new line
Carefull!!!

The identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes.

$str = <<<END
Welcome
to
Webpedia
END;
echo $str;
Result://Welcome to Webpedia 

Leave a Reply

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