Strings in PHP
What is Strings in PHP?
A string is a series of characters. There are exactly 256 different characters possible. The present stable versions of PHP – PHP4 and PHP5, have no native support for Unicode. There aren’t string length limitations in PHP except for the server’s available memory and the configuration of the php.ini settings file.
The string, like a variable, will have to be created first. There are two ways to use a string in PHP – you can store it in a function or in a variable. In the example below, we will create a string twice – the first time storing it in a variable, and the second time – in a function, in our case – an echo
String Basic Example
1 2 3 4 5 |
<?php $myString = "This is a string!"; echo "This is a string!"; echo $myString; ?> |
The output of this PHP file will be:
This is a string!This is a string!
String basics
1. Single quote strings (‘ ‘) –
Single quotes represent ‚simple strings,‛ where almost all characters are used literally
2. Double quote strings(” “) –
Complex strings‛ that allow for special escape sequences (for example, to insert special characters) and for variable substitution
1 2 3 |
$a="PHPGURUKUL"; echo ‘Hello $a’; echo "Hello $a n welcome"; |
Output
Hello $a
Hello PHPGURUKUL
welcome
Clearly, this “simple” syntax won’t work in those situations in which the name of the variable you want to interpolate is positioned in such a way inside the string that the parser wouldn’t be able to parse its name in the
way you intend it to. In these cases, you can encapsulate the variable’s name in braces.
1 2 3 4 |
$me = ’Davey’; $names = array (’Anuj’, ’Sanjeev’, ’Rahul’); echo "There cannot be more than two {$me}s!"; echo "Citation: {$names[1]}[1987]"; |
3. The Heredoc Syntax
Used to declare complex strings, the functionality it provides is similar to double quotes, with the exception that, because heredoc uses a special set of tokens to encapsulate the string, it’s easier to declare strings that include many double-quote characters.
1 2 3 4 |
$who = "World"; echo <<<TEXT So I said, "Hello $who" TEXT; |
Escaping Literal Values
• All three string-definition syntax feature a set of several characters that require escaping in order to be interpreted as literals.
1 2 3 4 |
echo ’This is ’my’ string’; $a = 10; echo "The value of $a is "$a"."; echo "Here’s an escaped backslash:"; |
String as arrays
You can access the individual characters of a string as if they were members of an array
1 2 |
$string = ’abcdef’; echo $string[1]; // Outputs ’b’ |
String comparison == and ===
1 2 3 4 |
$string = ’123aa’; if ($string == 123) { // The string equals 123 } |
- You’d expect this comparison to return false, since the two operands are not the same. However, PHP first transparently converts the contents of $string to the integer 123, thus making the comparison true.
- Naturally, the best way to avoid this problem is to use the identity operator ===