Easy Tutorial
❮ Pdo Lastinsertid Func Xml Set Processing Instruction Handler ❯

PHP String Variables


String variables are used to store and manipulate text.


String Variables in PHP

String variables are used to hold values containing characters.

After creating a string, we can manipulate it. You can use the string directly in a function or store it in a variable.

In the following example, 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;
?>

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

Now, let's look at some common functions and operators for manipulating strings.


PHP Concatenation Operator

In PHP, there is only one string operator.

The concatenation operator (.) is used to concatenate two string values.

The following example demonstrates how to concatenate two string variables:

Example

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

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

Tip: In the above code, we used the concatenation operator twice. This is because we needed 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 (number of bytes).

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

Example

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

The above code will output: 12

Tip: strlen() is often used in loops and other functions where 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 text within a string.

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

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

Example

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

The above code will output: 6

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


Complete PHP String Reference Manual

For a complete reference manual of all string functions, please visit our PHP String Reference Manual.

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

❮ Pdo Lastinsertid Func Xml Set Processing Instruction Handler ❯