PHP string tutorial - Variable parsing in string


Home - Tutorials - Basics

A detailed description how to use PHP strings and string manipulation functions.

Tutorial info:


Name:PHP string tutorial
Total steps:3
Category:Basics
Level:Beginner

Bookmark PHP string tutorial



Step 2 - Variable parsing in string


PHP string tutorial

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:

 

Code:
  1. <?php
  2. $userName = "Peter";
  3.  
  4. echo 'Hello '.$userName.', nice to see you again!';
  5. ?>

 

Using double quotes you can make it more simple:

 

Code:
  1. <?php
  2. $userName = "Peter";
  3.  
  4. echo "Hello $userName, nice to see you again!";
  5. ?>

 

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:

Code:
  1. <?php
  2. $userName = "Peter";
  3.  
  4. echo "$userNames website";
  5. ?>


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: 
Code:
  1. <?php
  2. $userName = "Peter";
  3.  
  4. echo "${userName}s website";
  5. echo "{$userName}s website";
  6. ?>

 

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:
  1. <?php
  2. $users = array('U1' => "Peter");
  3.  
  4. echo "Hello {$users['U1']}, nice to see you again!";
  5. ?>


You can read about string concatenation in the next section.





Previous Step of PHP string tutorialNext Step of PHP string tutorial


Tags: php string, php string function, string, php



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.1396