Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP string variable


May 10, 2021 PHP


Table of contents


PhP string variable

A string is a series of characters, each of which is equivalent to one byte.

String variables are used to store and process text.


String variable in PHP

String variables are used to contain values with characters.

After we create the string, we can work on it. You can use strings directly in functions, or store them in variables.

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

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

Run an instance . . .

PHP string variable Note: When you assign a text value to a variable, remember to place single or double quotes on the text value.

Now, let's look at some of the functions and operators of commonly used action strings.


PHP-and-place operators

In PHP, there is only one string operator.

The sides-by-place operator (.) is used to connect two string values.

The following example shows how to connect two string variables together:

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

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

Tip: In the code above, we've used the synth 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 the string (number of characters).

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

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

Run an instance . . .

The above code will output: 12

Tip: Strlen() is often used in loops and other functions because it is important to determine when the 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 find a character or a specified piece of text within a string.

If a match is found in the string, the function returns the first matching character position. If no match is found, FALSE is returned.

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

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

Run an instance . . .

The code above will output: 6

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


Complete PHP String reference manual

To view the full reference manual for all string functions, please visit our PHP String reference manual.

This reference manual provides a brief description of each function and an example of its application!