PHP Strings
PHP - String Creation
In PHP the string function allows you to manipulate strings. A string can be used directly in a function or it can be stored in a variable. Strings are probably the most important thing in PHP as in order to complete almost any task you will have to deal with strings. So to get started let’s have a look at the basics of creating strings. There are Three basic ways of creating strings
- Strings Creation With Double Quotes
- String Creation With Single Quotes
- String creation with Heredoc
In PHP, a variable must start with $ sign followed by variable name. The string value must be wrapped in double or quotes.
Strings Creation With Double Quotes:
Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote string.
In PHP Strings can be wrapped in double or singles quotes. Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote string. Using double quotes is the most used method.
Strings in double quotes are interpolated. This means that if you put a variable inside it, it will return the value of that variable.
For example, when you use the $ sign within double quotes it is treated as php variable and will not show up in the output
An Example:
$myStr = "Welcome";
We could add to this example by echoing the output value of myStr for example:
$myStr = "Welcome";
echo "$myStr everyone!";
The above example will output "Welcome everyone" NOT "$myStr everyone"
Strings Creation With Single Quotes:
In PHP if you want to use a single-quote within the string you have to escape the single-quote with a backslash \ . Like this: \' !
Single quotes should be used when writing HTML code within
Since HTML tag attributes use double quotes with in themselves and since using double quotes in HTML tags is the convention, therefore it is advisable to use single quotes when wrapping a HTML code in PHP.
Example: (note double quotes in html type=”” – this only works because you have opened with a single quote.)
<?php echo ''; ?>
Strings Creation With Heredoc:
PHP has created a string creation tool called heredoc that allows you create multi-line strings without using quotations. Creating strings with heredoc is more difficult and can lead to more problems.
In order to use heredoc, you need to open a string using <<< and some identifier, for example TEXT. Then you should type your text. To close the heredoc, repeat the identifier followed by a semicolon (TEXT;).
- Use <<< and some identifier that you choose to begin the heredoc
- Repeat the identifier followed by a semicolon to end the heredoc string creation.
- The closing sequence TEST; must occur on a line by itself and cannot be indented!
<?php $my_string = <<
Thats It.
