Monday, June 1, 2009

PHP - Strings

String

A string variable is used to store and manipulate text.
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.

<?php
$myString = "This is a string!";
echo "This is a string!";
echo $myString;
?>

Display:

This is a string!This is a string!

Single quotes and Double quotes.

There are two ways of quoting when you can specify a string in PHP – single quotes or double quotes.

Example for Single quotes

<?php
$my_string = 'Hello vn4000';
echo 'Hello vn4000';
echo $my_string;
?>

Example for double quotes

<?php
$my_string = "Hello vn4000";
echo "Hello vn4000";
echo $my_string;
?>

The two methods above are the traditional way to create strings in most programming languages. PHP introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations.

Example

<?php
$my_string = <<<TEXT
My
favorite
language
is
PHP
TEXT;
echo $my_string;
?>