Strings

0 latisha55n33679 December 12, 2020

Strings are an array of characters i.e they are characters arranged one after another in memory. Thus, the character array is also known as a string. Each character within the string will be stored within one element of an array. A string is used by PHP to manipulate text such as words and characters.

We can declare the string in four different ways.

1. Single Quoted

We can declare the string in PHP using Single Quote . If we want a single quote in the string then we have to use \ (escape sequence) as shown in the below example.

<?php

echo "Welcome to Code Help Pro";

echo "You\'re welcome";
//Output : You're welcome

echo "You are in C:\\suresh\hello.txt";
//Output : You are in C:\suresh\hello.txt

?>

Note: You can’t use variables inside a single quote. We can use variables inside the double quotes which we will discuss below.

2. Double Quoted

To declare the string, We can use double Quotes . If we want a single quote in the string then we have to use \ (escape sequence).

This is the most used method to declare the variables. We can also render the variables inside the double quotes as shown below.

<?php

$website = "Code Help Pro";
echo "Welcome to $website.";
//Output : Welcome to Code Help Pro.

?>

3. Heredoc Syntax

Heredoc is another way to declare the strings <<<. After this operator, We must provide identifier followed by the new line.

Note: We must note that the closing identifier must not contain any character, except a semi-column, and also end identifier must not be indented.

#Invalid Example

<?php

$str = <<<EOD
This is the example
string. Please ignore
this paragraph.
        EOD;

?>

//Identifier should not be indented

#valid Example

<?php

$str = <<<EOD
This is the example
string. Please ignore
this paragraph.
EOD;

?>

We can also render variables inside the heredoc syntax.

Variable parsing

When we declare the variable inside the double quotes or heredoc syntax then variables are parsed. We can declare the variable inside the single quotes as shown below.

<?php

$website = "Code Help Pro";
echo "Welcome to $website";
echo "Welcome to {$website}";
//Output: Welcome to Code Help Pro

?>

In the above program, We have parsed the variable inside the double quotes in three ways. All these methods are valid and work the same.

Similarly, we can parse the array index and object property inside the double quotes or heredoc syntax.

<?php

$array = array("apple", "banana", "orange");
echo "I like $array[0].\n";

class fruits{
    public $one = "apple";
    public $two = "banana";
    public $three = "orange';
}
$fruits = new fruits();
echo "I like $fruits->one.";

?>

The output of above program is

I ike apple.
I like apple.