Step 1 - PHP string basic
You can set a string in three different ways. It's up to you what method do you use, all have pros.
- The
first and most known way is to specify a string in single quotes.
Similar to other programing languages you need to use backslash '\' if
you want to display a single quote in your text.
- The
second option to use double quotes. Between double quotes you can use
more escape character in your string. Besides this if you put a
variable in the string then PHP will interpret it and display the
content of the variable.
Code:
Here the most important part is the string defined as $str_3 and its output in line 8 will result this:Output:This is a Internal string - And
last you can use heredoc as well. In this case you define your text
between heredoc identifiers. In this case it is DEMO. You need to start
it with the operator <<< and then the identifier. If you are
ready you need to close the heredoc part by adding the identifier again
at the beginning of a new line like this:
As
you can see the output is in the same formatting - text indent, new
lines - as it was defined. You can use variables in case of heredoc as
well as in case of double quoted strings.
The 2.
case is the most interesting string definition version so let's see a
bit more how to insert a variable inside a string. (You can use
variables in case 3. as well but heredoc is not so common.)
Step 2 - Variable parsing in string
Time to time you need to compose a complete text from sub strings
and variables. For example if you want to greet your visitor you want
to display a text like:
"Hello Peter, nice to see you again!"
Of
course you can not hard code the user name but you want to use a
variable like $userName. If you use single quoted strings then you can
display your text like this:
Using double quotes you can make it more simple:
The more variable you need to use the bigger is the difference.
After the basic case let's see some more complex variable parsing. What if you want to display the text:
"Peters website"
Using the above examples the $userName variable contains only the string Peter and if you compose your string as before:
You will get a warning and the result is not what you expected:
Output:Notice: Undefined variable: userNames in Z:\wdocs\test.php on line 4 website
To solve this problem you need to enclose the variable in curly braces like in the following example:
As you can see it is possible to enclose only the variable name without the $ sign or the complete variable.
You have to use this solution in case of arrays as well in the following way:
Code:
<?php echo "Hello {$users['U1']}, nice to see you again!"; ?>
No comments:
Post a Comment