PHP Lessons - Lesson 3 - PHP String Variables
In the previous lesson, we discussed that PHP supports variables. In this lesson, we'll take a look at one type of variable — string variables.
String variables in PHP are used to store values that consist of characters. A PHP string can be saved in a variable. Below is a PHP script that assigns the text "Hello, World!" to the string variable $txt
:
<?php
$txt = "Hello, World!";
echo $txt;
?>
The result of the code above:
Hello World!
Now let's try a few different functions and operators to manipulate strings.
String Concatenation Operator in PHP
PHP has only one string operator: the concatenation operator, which is a period .
. This operator is used to combine two string values. To concatenate two string variables, use the concatenation operator like this:
<?php
$txt1 = "Hello, World!";
$txt2 = "How are you?";
echo $txt1 . " " . $txt2;
?>
The result of the code above:
Hello, World! How are you?
As you can see, we used the concatenation operator twice. That's because we inserted a third string — a space — between the two messages to separate them.
You may also have noticed that the output is printed on one line. To print it on a new line, you can use HTML tags like <br />
or <p></p>
:
<?php
$txt1 = "Hello, World!";
$txt2 = "How are you?";
print $txt1 . "<br />" . $txt2;
?>
Result:
Hello, World!
How are you?
Using the <p>
tag:
<?php
$txt1 = "Hello, World!";
$txt2 = "How are you?";
print "<p>" . $txt1 . "</p><p>" . $txt2 . "</p>";
?>
Same visual result, but different HTML output:
<p>Hello, World!</p>
<p>How are you?</p>
PHP strlen() Function
The strlen()
function returns the length of a string. Let's get the length of a string:
<?php
echo strlen("Hello, World!");
?>
Result:
12
Knowing the length of a string is useful in loops or other logic where it's important to detect the end of a string.
PHP strpos() Function
The strpos()
function is used to find the position of a substring in a string. If a match is found, it returns the position of the first match; if not, it returns FALSE
. Let's try finding the word "World" in our string:
<?php
echo strpos("Hello, World!", "World");
?>
Result:
7
The position is 7 because string positions start at 0, not 1.