How To Work with Strings in PHP
A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. All written communication is made up of strings. As such, they are fundamental to any programming language.
In this article, you will learn how to create and view the output of strings, how to use escape sequences, how to concatenate strings, how to store strings in variables, and the rules of using quotes, apostrophes, and newlines within strings in PHP.
Single and Double-Quoted Strings
You can create a string in PHP by enclosing a sequence of characters in either single or double quotes. PHP will actually interpret the following strings differently:
'This is a string in single quotes.'
"This is a string in double quotes."
Before output, double-quoted strings will evaluate and parse any variables or escape sequences within the string. Single-quoted strings will output each character exactly as specified. The exception for single-quoted strings is a single quote (and backslash when needed).
If you were to echo this string in PHP:
'Sammy says: "This string\'s in single quotes." It required a backslash (\) before the apostrophes (\\\'), but do not use (\") with the double quotes.'
It would return this output:
OutputSammy says: "This string's in single quotes." It required a backslash (\) before the apostrophes (\'), but do not use (\") with the double quotes.
If you don’t include a backslash before the apostrophe in the single-quoted string, PHP will end the string at that point, which will cause an error. Since you’re using single quotes to create our string, you can include double quotes within it to be part of the final string that PHP outputs.
If you want to render the \’ sequence, you must use three backslashes ( \\\’ ). First \\ to render the backslash itself, and then \’ to render the apostrophe. The sequence \» is rendered exactly as specified.
"Sammy says: \"This string's in double quotes.\" It requires a backslash (\) before the double quotes (\\\"), but you MUST NOT add a backslash before the apostrophe (\')."
OutputSammy says: "This string's in double quotes." It requires a backslash (\) before the double quotes (\"), but you MUST NOT add a backslash before the apostrophe (\').
As with the single-quoted string, if a backslash is not included before the double quotes in the double-quoted string, PHP will end the string at that point, which will cause an error. Since the double-quoted string is not ended with a single quote, you add the apostrophe directly to a double-quoted string. A double-quoted string will output \’ with either a single or double backslash used with the apostrophe.
To output the \» sequence, you must use three backslashes. First \\ to render the backslash itself, and then \» to render the double quote. The sequence \’ is rendered exactly as specified.
The \ is known as an escape character. Combined with a secondary character, it makes up an escape sequence. Now that you have an understanding of strings, let’s review escape sequences.
Escape Sequences
An escape sequence tells the program to stop the normal operating procedure and evaluate the following characters differently.
In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.
Here are some common escape sequences for double-quoted strings:
- \» for a double quote
- \\ for a backslash
- \$ to render a dollar sign instead of expanding the variable
- \n for a new line
- \t for a tab
Here is an example of how you can use these sequences in a string:
"\"What type of \$ do sharks use?\"\n\tSand dollars!"
Output"What type of $ do sharks use?" Sand dollars!
Using escape sequences gives us the ability to build any string required while including these special characters.
Creating and Viewing the Output of Strings
The most important feature of double-quoted strings is the fact that variable names will be expanded, giving you the value of the variable. You can use a variable to stand in for a string or use a string directly. You output the string by calling the echo function:
$my_name = "Sammy"; echo 'Name is specified using the variable $my_name.'; echo "\n"; // escape sequence for newline character echo "Hello, my name is $my_name. It's stored in the variable \$my_name.";
The $my_name variable is created on the first line. On the second line, the echo function is used to output a string in single quotes. Using the $my_name variable within this single-quoted string displays the characters exactly as they are written, so we will see the variable name instead of its value.
On the fourth line, we use the echo function again, but we are using double quotes this time. This time the variable is expanded to show the value in the first sentence. In the next sentence, there is a \ before the $ to explicitly tell the string to display a $ character and not expand the variable.
OutputName is specified using the variable $my_name. Hello, my name is Sammy. It's stored in the variable $my_name.
Note: When string evaluation is not a concern, you may choose to use either single quotes or double quotes, but whichever you decide on, you should be consistent within a program. Single quotes may be marginally faster.
With an understanding of how to create and view the output of strings, let’s move on to see how you can manipulate strings.
String Concatenation
Concatenation means joining strings together, end-to-end, to build a new string. In PHP, there are two main ways to concatenate a string.
The first is to include a string variable within a double-quoted string. This was shown in the previous step and in the following:
$answer = "Chews wisely."; echo "What do sharks do when they have a big choice to make? $answer";
Running this code will combine the string and the $answer variable, which is set to Chews wisely. :
OutputWhat do sharks do when they have a big choice to make? Chews wisely.
A second way to concatenate strings is to use the . operator.
Let’s combine the strings «Sammy» and «Shark» together with concatenation through an echo statement:
This code uses the . operator to combine the «Sammy» string and the «Shark» string without a space in between.
If you would like whitespace between the two strings, you must include the whitespace within a string, like after the word Sammy :
You cannot use concatenation to combine a string with an integer:
This will produce an error:
OutputParse error: syntax error, unexpected '.27' (T_DNUMBER), expecting ';' or ',' in php shell code on line 1
If you put «27» within quotes, it will evaluate as a string.
PHP is a loosely typed language, which means that it will try to convert the data it is given based on the request. If you set a variable to 27 , when used in concatenation with a string, PHP will parse the variable as a string:
$my_int = 27; echo "Sammy" . $my_int;
You’ve covered the two main ways to concatenate, or combine, strings. Sometimes you may want to replace, or add to, the string completely. Next, let’s explore how PHP allows you to overwrite or update a string.
Updating a String
Normal variables in PHP are mutable, which means they can be changed or overwritten. Let’s explore what happens when you change the value for the $my_name variable:
$my_name = "Sammy"; echo $my_name . "\n"; $my_name = "Shark"; echo $my_name;
First, the variable was set to «Sammy» and displayed using echo . Then it was set to «Shark» , overwriting the variable, so that when echo was called a second time, it displayed the new value of «Shark» .
Instead of overwriting the variable, you can use the concatenating assignment operator .= to append to the end of a string:
$my_name = "Sammy"; $my_name .= " Shark"; echo $my_name;
First, you set the $my_name variable to «Sammy» , then used the .= operator to add » Shark» to the end of it. The new value for $my_name is Sammy Shark .
To prepend to the beginning of a string, you would overwrite while using the original string:
$my_name = "Shark"; $my_name = "Sammy " . $my_name; echo $my_name;
This time, you first set the $my_name variable to «Shark» , then used the = operator to override the $my_name variable with the new string «Sammy » , combined with the previous value of the $my_name variable, which before being overridden is «Shark» . The final value for $my_name is Sammy Shark .
Overwriting, appending, and prepending give us the ability to make changes and build the strings required for our applications.
Whitespace in Strings
Because PHP does not care about whitespace, you can put as many spaces or line breaks within your quotes as you would like.
echo "Sammy The (silly) Shark";
TEXT OutputSammy The (silly) Shark
Keep in mind that HTML renders whitespace differently. New lines require a
tag, so even though your source may have new lines, you will not see those new lines displayed on a web page. Similarly, no matter how many spaces there are in your code, only a single space is displayed between characters.
HTML OutputSammy The (silly) Shark
Clean and consistent use of whitespace is one of the best tools for making code more readable. Since PHP essentially ignores whitespace, you have a lot of flexibility that you can use to your advantage. An integrated development environment (IDE) can help you stay consistent with your code and use of whitespace.
Conclusion
Being able to control the way our strings are rendered is essential for communicating with an application’s end user. By updating and combining variables that include special characters, you can clearly communicate while keeping repetition to a minimum.
As you continue to work with strings, keep in mind these three aspects:
- Pay special attention to quotes within your strings.
- Use concatenation to combine your strings.
- Use variables to make your strings reusable.
If you would like to read more about PHP, check out the PHP topic page.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Code in PHP
PHP is a popular server scripting language known for creating dynamic and interactive web pages.
Объявить переменную string php
While waiting for native support for typed arrays, here are a couple of alternative ways to ensure strong typing of arrays by abusing variadic functions. The performance of these methods is a mystery to the writer and so the responsibility of benchmarking them falls unto the reader.
PHP 5.6 added the splat operator (. ) which is used to unpack arrays to be used as function arguments. PHP 7.0 added scalar type hints. Latter versions of PHP have further improved the type system. With these additions and improvements, it is possible to have a decent support for typed arrays.
function typeArrayNullInt (? int . $arg ): void >
function doSomething (array $ints ): void (function (? int . $arg ) <>)(. $ints );
// Alternatively,
( fn (? int . $arg ) => $arg )(. $ints );
// Or to avoid cluttering memory with too many closures
typeArrayNullInt (. $ints );
function doSomethingElse (? int . $ints ): void /* . */
>
$ints = [ 1 , 2 , 3 , 4 , null ];
doSomething ( $ints );
doSomethingElse (. $ints );
?>
Both methods work with all type declarations. The key idea here is to have the functions throw a runtime error if they encounter a typing violation. The typing method used in doSomethingElse is cleaner of the two but it disallows having any other parameters after the variadic parameter. It also requires the call site to be aware of this typing implementation and unpack the array. The method used in doSomething is messier but it does not require the call site to be aware of the typing method as the unpacking is performed within the function. It is also less ambiguous as the doSomethingElse would also accept n individual parameters where as doSomething only accepts an array. doSomething’s method is also easier to strip away if native typed array support is ever added to PHP. Both of these methods only work for input parameters. An array return value type check would need to take place at the call site.
If strict_types is not enabled, it may be desirable to return the coerced scalar values from the type check function (e.g. floats and strings become integers) to ensure proper typing.
same data type and same value but first function declare as a argument type declaration and return int(7)
and second fucntion declare as a return type declaration but return int(8).
function argument_type_declaration(int $a, int $b) return $a+$b;
>
function return_type_declaration($a,$b) :int return $a+$b;
>