Strings in PHP

596 0

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 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
Basic Example

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

Hello $a
Hello baabtra

Clearly, this “simple” syntax won’t work in those situations in which the name of the variable you want to interpolated 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.

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.

Escaping Literal Values
• All three string-definition syntax feature a set of several characters that require escaping in order to be interpreted as literals.

String as arrays
You can access the individual characters of a string as if they were members of an array

String comparison == and ===

  • 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 ===



In this article

Join the Conversation