PHP String Variables


String variables are used to store and process text.


String Variables in PHP

String variables are used to contain values with characters.

After creating a string, we can manipulate it. You can use strings directly in functions, or store them in variables.

In the example below, we create a string variable named txt and assign it the value "Hello world!". Then we output the value of the txt variable:

Example

<?php
$txt
="Hello world!";
echo
$txt;
?>

Run Example »

lamp Note:When you assign a text value to a variable, remember to add single or double quotes to the text value.

Now, let's take a look at some commonly used functions and operators for manipulating strings.


PHP Concatenation Operator

In PHP, there is only one string operator.

Concatenation operator.is used to concatenate two string values.

The example below demonstrates how to concatenate two string variables together:

Example

<?php
$txt1
="Hello world!";
$txt2="What a nice day!";
echo
$txt1 . " " . $txt2;
?>

The code above will output: Hello world! What a nice day!

Tip:In the code above, we used the concatenation operator twice. This is because we need to insert a space between the two strings.


PHP strlen() Function

Sometimes it is useful to know the length of a string value.

The strlen() function returns the length of a string (in bytes).

The example below returns the length of the string "Hello world!":

Example

<?php
echo strlen("Hello world!");
?>

Run Example »

The code above will output: 12

Tip:strlen() is often used in loops and other functions, because it is important to determine when a string ends. (For example, in a loop, we need to end the loop after the last character in the string.)


PHP strpos() Function

The strpos() function is used to search for a character or a specified piece of text within a string.

If a match is found in the string, the function returns the position of the first matched character. If no match is found, it returns FALSE.

The example below searches for the text "world" in the string "Hello world!":

Example

<?php
echo strpos("Hello world!","world");
?>

Run Example »

The code above will output: 6

Tip:In the example above, the position of the string "world" is 6. The reason it is 6 and not 7 is that the position of the first character in a string is 0, not 1.


Complete PHP String Reference Manual

To view the complete reference manual for all string functions, please visit ourPHP String Reference Manual。

This reference manual provides a brief description and usage examples for each function!

Other Extensions