Posted by on .

Php String Handling

php string handlingPhp String is a sequence of character with a sensible meaning. In any programming language string manipulation and string handling has a wide role. In case of php all the output comes after php execution are in the form of string hence string handling in php is a most important concept  in php programming.

Php string can be used in following  types.

  • Echo
  • Print
  • Heredoc

To print a string at a php generated page echo is a most largely used construct, Because of echo is an language construct so that parentheses are also not required. Echo can be used  with single quotes and echo with double quotes.

Echo with single quotes
When we use echo with single quotes at that time interpreter will not check any variable or escape character it will print as it is whatever given into these single quotes, Means interpreter not involve when we use echo with single quotes.

<?php

$a=192;
Echo’$a’;

?>

Output : $a

Hence in the above example we see output is $a not the value of $a means interpreter not interpret the value of variable $a, It prints exactly that is printed in between single quotes.

Echo with double quotes
Echo with double quotes is an interpreted construct of php all the variables used in between double quotes will be interpreted and their value comes into the output.

<?php

$a=192;
Echo”$a”;

?>

Output : 192

As we see output is 192 , in this case $a interpreted and its value i.e. 192 comes in output.

Php String with Print()
Print is a function is also used to display string at php generated page, and can be represented as print( string) . Print function always returns 1 and slightly slower then echo.
Print also can be used with single quotes and double quotes and the difference is same as in echo i.e. in single quotes variables are treated as string and to interpreted while in double quotes variables interpreted and their values will be printed.

<?php

$a=192;
Print(‘$a’);
Output : $a
Print(“$a”);

?>

Output : 192

Heredoc in php string
Heredoc is also an option to represent strings in php while heredoc has an proper syntax where  “ <<<”  after this operator an identifier is used then in new line string that need to be printed is start then after same identifier used to close the quotation.
These identifier has an specific nomenclature it only contains alphanumeric characters and underscores. Closing identifiers must be starts in the first column of the line.

<?php

$var = <<<EOD
heredoc example
Using multiline example
EOD;

?>

Heredoc guidelines is the main concern and take care for those to avoid any headaches.