The PHP String is a series of characters (specifically alphabetical letters, numbers, etc. ) that is useful for storing or utilizing texts.
Moreover, there are four ways to express strings in PHP.
Specifically, through enclosing texts in a single quote (‘ ‘), double quote (” “), heredoc syntax, and newdoc syntax.
What is a string function?
The string function in PHP is a method that works with data (text), queries (information), or both.
The string functions implement the function as string object attributes and methods.
In some instances, a string is represented as a list of character codes; hence, all list-manipulation techniques could be categorized as string functions.
PHP further supports immutable strings and returns a copy (in newly allocated dynamic memory).
A basic example of a string function is the length() function, which measures the count of characters in a string.
Example:
The string “IT Source Code” when used with the length function, will return an output of 14.
This means that the string has 14 characters including the spaces.
What are the types of strings in PHP?
There are four ways to specify the PHP strings and these are:
- single-quoted – Programmers can use a single quote to display the string in PHP, through the use of the
' '
symbol.
- double quoted – This expression uses double quotes
" "
in displaying strings.
- heredoc syntax – Its syntax is unique from the single and double-quoted strings but works similarly with
" "
.
- newdoc syntax (since PHP 5.3) – this, on the other hand, has a similar syntax with heredoc but with
' '
in its first tag.
These types of strings can be applicable to different string functions available in PHP programming.
Moreover, we will try the different types of strings in each string function in the following discussions and topics.
1. Single Quoted
One of the ways we can express string in PHP is to enclose a test, letter, word, or phrase in a single quote like 'Sample Text'
.
This method is the easiest way to specify that the given line of code or expression is a string.
In some circumstances when you need to add special characters within the string, you may use the PHP escape string tags or backslash (\). The backslash (\
) enables the program to read the string simultaneously even with special characters.
For example, when we want to display the phrase 'Prince's car'
, our line of code will look like the following:
<?php
$txt = 'Prince\'s car';
echo $txt;
?>
This code will then display the output like the given example.
Prince's car
Now, we will have different examples to demonstrate the use of a single quote in PHP strings.
Example 1:
For our first example, we will try to display a simple phrase through the PHP string using a single quote.
<?php
$txt = 'IT Source Code';
echo $txt;
?>
Output:
IT Source Code
The first example demonstrates the use of a single quote to display the string. Therefore, the single quote string is useful for simple phrases without special characters.
Example 2:
The second example will try the single-quoted strings in displaying multiple lines of strings. For this, we will have the following code:
<?php
$txt = 'IT Source Code,
Where source codes
are no longer a problem.';
echo $txt;
?>
Output:
IT Source Code, Where source codes are no longer a problem.
The output shows that the single-quoted string disregards even if the string is in multiple lines as long as they are within the quote, they were read as a single string.
Example 3:
This third example demonstrates how the single-quoted string works with escape string tags and special characters.
<?php
//example single-quoted string with special characters
$txt1 = '"ITSourceCode.com" provides lot of free source codes.';
//example single-quoted string with escape string tags
$txt2 = 'ITSourceCode\'s tutorials were great!';
echo $txt1."<br/>".$txt2;
?>
Output:
"ITSourceCode.com" provides lot of free source codes. ITSourceCode's tutorials were great!
As seen in the output, the example code justifies that the single-quoted string is capable of working even with a special character and with the application of backslash or escape string tags.
Remember that the escape string tags only enable you to show the exact output of strings with special characters not to change the string.
2. Double Quoted
Another way of expressing strings in PHP is by enclosing a text, letter, word, or phrase in a double quote ("Sample Text"
) symbol or expression.
However, unlike the single-quoted string, double-quoted strings do not need escape string tags to display special characters in the output.
hus, the double quote can support special characters in a string without the use of escape string tags.
Now let us have some examples of implementing the double-quoted strings in different scenarios.
Example 1:
The first example in testing the PHP double-quoted string is with plain messages or text without any special characters.
<?php
$txt = "Welcome to ITSourceCode!";
echo $txt;
?>
Output:
Welcome to ITSourceCode!
This example shows the implementation of using double quotes in PHP strings. It turns out that the double-quoted strings work the same as the single-quoted strings for plain phrases or texts.
Example 2:
The next example will try to use double quotes within the double-quoted PHP strings.
<?php
$txt = "Welcome to "ITSourceCode!"";
echo $txt;
?>
Output:
PHP Parse error: syntax error, unexpected 'ITSourceCode' (T_STRING) in /home/1ErLXU/prog.php on line 6
The output has proven that you cannot place another double quote within the double-quoted string. The program will read this double quote as another string or else, it will raise an error.
Remember that you cannot use a double quote within the double-quoted string, though you can use other special characters. However, you can use a double quote by applying the escape string tag or backslash (\
) which will look like \"ITSourceCode"\
.
Example 3:
The next example will try to use the double-quoted strings with multiple lines of code.
<?php
$txt = "Welcome to ITSourceCode!
Where source codes
are no longer a problem.";
echo $txt;
?>
Output:
Welcome to ITSourceCode! Where source codes are no longer a problem.
The double-quoted strings also disregard the multiple lines of string as long as to is enclosed within the double quote as the output shows.
Example 4:
Now, let us use the double-quoted strings in interpreting the values of variables.
<?php
$num = 2022;
echo "We are now in the year $num.";
?>
Output:
We are now in the year 2022.
This example proves that the PHP string enclosed in double quotes can interpret the value of a variable. In the string, "We are now in the year $num."
, the variable is $num
and its value is 2022
.
Therefore, double-quoted strings are applicable for variable value interpretation.
3. Heredoc
Aside from single quotes and double quotes, we can also use the heredoc to show strings in PHP.
Heredocs are equivalent to strings within double quotes. Therefore, all variables within the string will return with their respective values.
Additionally, in Heredoc syntax, an identifier is provided after the heredoc (<<<
) operator and text are then written on a new line.
To close the quotation, the string is attached to itself, followed by the same identifier. This ending identifier must begin on a new line, free of any spaces or tabs.
You should also be aware that the heredoc in PHP has its naming rules. Therefore your identifier must adhere to the requirement that names can only contain letters, digits, and underscores.
Let us apply the heredoc’s definition and naming rules in the following examples.
Example 1:
This example will apply to a valid program and demonstrate how the heredoc works in delivering PHP strings.
<?php
$txt = <<<tag
Welcome to ITSourcecode
tag;
echo $txt;
?>
Output:
Welcome to ITSourcecode.
Example 1 shows how to do the exact placement of strings in PHP through heredoc.
The delimiter tag
next to the opening of the string (<<<
) is an open-close tag literal and it informs the program that the data in it is a string.
Example 2:
The next example will test the heredoc file with an invalid declaration of string and we’ll see how would this expression react.
<?php
$txt = <<<tag
Welcome to ITSourcecode.
tag;
echo $txt;
?>
Output:
PHP Parse error: syntax error, unexpected end of file in /home/igrGe3/prog.php on line 14
The output of this example proves that no spaces or tabs are permitted before or after the identification and semicolon.
Therefore, the identifier cannot be indented and the identification must start on a separate line.
Example 3:
In this example, we will try if heredoc can interpret the value of a variable within the string.
<?php
$txt = Jane;
echo <<<tag
My name is $txt.
tag;
?>
Output:
My name is Jane.
The output of example 3 justifies that heredoc is similar to a double-quoted string, which can also print the variable’s value.
Example 4:
This time, we will have an example where we test the heredoc in a PHP string with multiple lines and see if it works like the preceding PHP string expressions.
<?php
echo <<<tag
My name is Jane.
I live in Negros,
and I am 30 years old.
tag;
?>
Output:
My name is Jane. I live in Negros, and I am 30 years old.
As shown in the output, the heredoc can also return a string in PHP with multiple lines. Therefore, programmers may use either the single quote, double quotes, or heredoc to deal with PHP strings with multiple lines.
Example 5:
The fifth example will show how to apply heredoc in a PHP string with class and variables.
This example gets more complex than the former examples, so take a good look and make sure you analyze the positioning and declaration of class and variables as well as its naming rules.
<?php
class heredocExample{
var $name;
var $text;
function __construct()
{
$this->name = 'Name';
$this->text = array('Text1', 'Text2', 'Text3');
}
}
$heredocExample = new heredocExample();
$str = 'Jane';
echo <<<TAG
My name is "$str". I am testing some $heredocExample->name example and {$heredocExample->example[1]}
it will print a capital 'A': \x41
TAG;
?>
Output:
My name is "Jane". I am testing some Name example and it will print a capital 'A': A
To explain the example, the program sets two variables, which are the $name
and the $text
. The variable $name
has the value 'Name'
, while the $text
has an array value containing 'Text1', 'Text2', 'Text3'
.
Now to display the output, the echo function containing the string includes the declared variables along with the class.
The class in example 5 is the heredocExample
and all the lines within its brackets are under it. So, the string only calls the class once, and it was called the first time the program ran.
What is PHP heredoc used for?
A heredoc is derived from the phrase “here document”, which is a file literal or an input stream literal. It is a portion of a source code file that is regarded as its own file. It is also one method for storing or printing strings in PHP.
Also, the data saved in heredoc is easier to read and less likely to be wrong than data saved in other variables because it uses indentation and new lines.
Heredoc is also used for a multiline string literal that uses the same syntax but keeps line breaks and other whitespace.
Here are the steps to follow when you store or print the heredoc files:
<<<
: First, every heredoc (here document) should start with this expression or symbol.- Delimiters (open and close tags): Next, a delimiter must be used after the
<<<
symbol to define the beginning of the document. Then, the same delimiter name is followed by a semicolon (;
) is used at the end of the heredoc page to specify its conclusion.
Remember that in heredoc, any non-alphanumeric, non-backslash, non-whitespace character may serve as a delimiter, and the leading whitespace preceding a valid delimiter is ignored silently.
4. Newdoc
Newdoc is another alternative way to define the string (str) in PHP. This newdoc is applicable for strings with multiple lines of code and for strings that must include important whitespaces or tabs (indentation).
The Newdoc is comparable to the Heredoc and follows the same regulations. The main difference is that newdoc does not perform the parsing.
In addition, newdoc is identified with three less than symbols (<<<
), followed by an identifier. However, its identifier is surrounded by single quotation marks (like 'identifier'
).
In simple words, heredoc is the same as double-quoted strings and newdoc is similar to single-quoted strings.
Now, let us have some examples demonstrating the application of newdoc in defining PHP strings.
Example 1:
The first example will demonstrate the newdoc application for plain PHP strings.
<?php
$str = <<<'DEMO'
Welcome to ITSourceCode.
DEMO;
echo $str;
?>
Output:
Welcome to ITSourceCode.
Example 2:
The example below will display output with invalid inputs.
<?php
$txt = <<<'tag'
Welcome to ITSourcecode.
tag;
echo $txt;
?>
Output:
PHP Parse error: syntax error, unexpected end of file in /home/bT386L/prog.php on line 14
Example 3:
This third example will try the newdoc if it can interpret variables’ values.
<?php
class heredocExample{
var $name;
var $text;
function __construct()
{
$this->name = 'Name';
$this->text = array('Text1', 'Text2', 'Text3');
}
}
$heredocExample = new heredocExample();
$str = 'Jane';
echo <<<'TAG'
My name is "$str". I am testing some $heredocExample->name example and {$heredocExample->example[1]}
it will print a capital 'A'.
TAG;
?>
Output:
My name is "$str". I am testing some $heredocExample->name example and {$heredocExample->example[1]} it will print a capital 'A'.
PHP string concatenation
After knowing the different types of defining strings in PHP, let us now discuss the PHP string concatenation.
String concatenation is the method of combining two different strings using the concatenation operator. In PHP, we can use the dot (.
) to concatenate two different strings and the dot-equal (.=
) symbol to assign concatenation.
Example 1:
Using operator (.
) to combine two PHP strings.
<?php
$FirstName = "Maria";
$LastName = "Labrador";
echo $FirstName.$LastName."<br/>";
echo $FirstName." ".$LastName;
?>
Output:
MariaLabrador Maria Labrador
Your output will display depending on how you want the program to deliver the string. Either of the declarations in the echo function will be fine.
Example 2:
Using operator (.=
) to assign and combine two PHP strings.
<?php
$txt = "Welcome to ";
$txt .= "ITSourceCode!";
echo $txt;
?>
Output:
Welcome to ITSourceCode!
Example Program to Convert String to int using Type Casting
To convert a PHP string into an integer, we can use type casting. This method requires the programmer to provide the literal (int) along with parenthesis before the string literal.
The expression returns the integer value of the string upon program execution.
Syntax:
The syntax of the type-casting method is:
$int_value = (int) $string;
Let us use the syntax of the type casting method to convert PHP strings into integers with the following examples.
Example 1:
First, we will try the type casting method with an integer (whole number) and see how it converts the PHP string.
<?php
$string = "10";
$int_value = (int) $string;
echo $int_value;
?>
Output:
10
The program’s output shows that the method works fine with the whole number as a string. As a result, the syntax $int_value = (int) $string
could directly convert the string "10"
into integer 10
.
Example 2:
In this example, we will try to use the typing cast method with a PHP string containing decimal or float.
<?php
$string = "4.13";
$int_value = (int) $string;
echo $int_value;
?>
Output:
4
As seen in the output of the example, the method disregards the decimal value of the whole number, which results in displaying only the whole number.
So, if the string has a floating-point value, the type casting takes out the decimal part and returns only the full integer.
Example Program to Convert String to int using intval()
Aside from typing cast, PHP has a built-in function that can convert string to integer (int) and it is by using intval().
The intval() function is one of the PHP built-in functions that deal with strings. Its function is to convert the string value into an integer or number.
Syntax:
To apply the intval() function, we should use its syntax which is:
$int_value = intval( $string );
Now let us test the functionality of intval() through the examples below.
Example 1:
The first example will show how to implement the intval() function in the program and how it works toward converting a string into an integer.
<?php
$string = "10";
$int_value = intval( $string );
echo $int_value;
?>
Output:
10
In this example, the intval() function can directly convert the string into an integer as shown in the output. Therefore, this function works the same as type casting when dealing with whole numbers.
Example 2:
This time, we will try the intval() function with floating numbers or strings with decimal values. Let us see how this function can handle decimals.
<?php
$string = "4.13";
$int_value = intval( $string );
echo $int_value;
?>
Output:
4
As the output display, the intval() function works the same as in the preceding example wherein it disregards the floating value and only returns the whole number.
Related Articles
- PHP Convert to String with Example
- Understanding Strings in PHP
- PHP in_array function With Examples
- Array Push PHP (With Detailed Explanation)
- PHP array_merge With Detailed Explanation
Summary
The PHP string tutorial complements the discussions that a programmer or even a beginner needs to understand strings.
This topic included the various types of defining PHP strings as well as the methods that can be implemented in them.
All in all, the PHP string tutorial with example programs discussed and highlighted that a string is a series of characters whether alphabets, numbers, or special characters used for manipulating text or as storage.