Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Language Reference : Types : Strings

Strings

A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.

Note:

It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.

Syntax

A string literal can be specified in three different ways.

Single quoted

The easiest way to specify a simple string is to enclose it in single quotes (the character ').

To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.

Note:

In PHP 3, a warning will be issued at the E_NOTICE level when this happens.

Note:

Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?php
echo 'this is a simple string';

echo
'You can also have embedded newlines in
strings this way as it is
okay to do'
;

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

Double quoted

If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:

Table2.1.Escaped characters

sequence meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation


Again, if you try to escape any other character, the backslash will be printed too! Before PHP 5.1.1, backslash in \{$var} hasn't been printed.

But the most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier (followed by new line) after <<<, then the string, and then the same identifier to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Warning:

It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system. This is \r on Macintosh for example. Closing delimiter (possibly followed by a semicolon) must be followed by a newline too.

If this rule is broken and the closing identifier is not "clean" then it's not considered to be a closing identifier and PHP will continue looking for one. If in this case a proper closing identifier is not found then a parse error will result with the line number being at the end of the script.

It is not allowed to use heredoc syntax in initializing class members. Use other string syntaxes instead.

Example2.3.Invalid example

<?php
class foo {
public
$bar = <<<EOT
bar
EOT;
}
?>


Heredoc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Example2.4.Heredoc string quoting example

<?php
$str
= <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
var
$foo;
var
$bar;

function
foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some
{$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>


Note:

Heredoc support was added in PHP 4.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to parse a variable, an array value, or an object property.

The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name.

<?php
$beer
= 'Heineken';
echo
"$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drank some $beers"; // won't work, 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>

Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.

<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote your array string keys
// and do not use {braces} when outside of strings either.

// Let's show all errors
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');

// Works but note that this works differently outside string-quotes
echo "A banana is $fruits[banana].";

// Works
echo "A banana is {$fruits['banana']}.";

// Works but PHP looks for a constant named banana first
// as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces. This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " . $fruits['banana'] . ".";

// Works
echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>

For anything more complex, you should use the complex syntax.

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because you can include complex expressions this way.

In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" to get a literal "{$"). Some examples to make it clear:

<?php
// Let's show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo
"This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong
// outside a string. In other words, it will still work but
// because PHP first looks for a constant named foo, it will
// throw an error of level E_NOTICE (undefined constant).
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use
// braces around arrays when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo
"You can even write {$obj->values[3]->name}";

echo
"This is the value of the var named $name: {${$name}}";
?>
Note:

Functions and method calls work since PHP 5.

Note:

Parsing variables within strings uses more memory than string concatenation. When writing a PHP script in which memory usage is a concern, consider using the concatenation operator (.) rather than variable parsing.

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array-brackets like $str[42] so think of a string as an array of characters.

Note:

They may also be accessed using braces like $str{42} for the same purpose. However, using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6.

Example2.5.Some string examples

<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];

// Get the third character of a string
$third = $str[2];

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];

// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';

// Alternative method using {} is deprecated as of PHP 6
$third = $str{2};

?>


Note:

Accessing by [] or {} to variables of other type silently returns NULL.

Useful functions and operators

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.

There are a lot of useful functions for string modification.

See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).

There are also functions for URL-strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, if you still didn't find what you're looking for, see also the character type functions.

Converting to string

You can convert a value to a string using the (string) cast, or the strval() function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the echo() or print() functions, or when you compare a variable value to a string. Reading the manual sections on Types and Type Juggling will make the following clearer. See also settype().

A boolean TRUE value is converted to the string "1", the FALSE value is represented as "" (empty string). This way you can convert back and forth between boolean and string values.

An integer or a floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers).

Note:

The decimal point character is defined in the script's locale (category LC_NUMERIC). See setlocale().

Arrays are always converted to the string "Array", so you cannot dump out the contents of an array with echo() or print() to see what is inside them. To view one element, you'd do something like echo $arr['foo']. See below for tips on dumping/viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use get_class(). As of PHP 5, __toString() method is used if applicable.

Resources are always converted to strings with the structure "Resource id #1" where 1 is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use get_resource_type().

NULL is always converted to an empty string.

As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselves. Look at the functions print_r() and var_dump() for better ways to print out values for debugging.

You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function serialize(). You can also serialize PHP values to XML structures, if you have WDDX support in your PHP setup.

String conversion to numbers

When a string is evaluated as a numeric value, the resulting value and type are determined as follows.

The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

<?php
$foo
= 1 + "10.5"; // $foo is float (11.5)
$foo = 1 + "-1.3e3"; // $foo is float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is integer (1)
$foo = 1 + "bob3"; // $foo is integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1; // $foo is float (11)
$foo = "10.0 pigs " + 1.0; // $foo is float (11)
?>

For more information on this conversion, see the Unix manual page for strtod(3).

If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:

<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>

Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.

Related Examples ( Source code ) » language.types.string




Code Examples / Notes » language.types.string

bishop

You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
   // end-of-line comment will be masked... so will regular PHP:
   echo ($test == 'foo' ? 'bar' : 'baz');
   /* c-style comment will be masked, as will other heredocs (not using the same marker) */
   echo <<<EOHTML
This is text you'll never see!        
EOHTML;
   function defintion($params) {
       echo 'foo';
   }
   class definition extends nothing     {
      function definition($param) {
         echo 'do nothing';
      }      
   }
   how about syntax errors?; = gone, I bet.
_EOC;
?>
Useful for debugging when C-style just won't do.  Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.
Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.


lelon

You can use the complex syntax to put the value of both object properties AND object methods inside a string.  For example...
<?php
class Test {
public $one = 1;
public function two() {
return 2;
}
}
$test = new Test();
echo "foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".
However, you cannot do this for all values in your namespace.  Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
const ONE = 1;
}
echo "foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.


php

You can also use a here document as an argument in a function call. Like this:
<?php
foo(<<<EOT
Example of string
spanning multiple lines
using heredoc syntax.
EOT
);
?>
Note: no semicolon after the EOT (just as when using quoted text)


kunal thaggarse

When saving the output of an HTML table as an excel sheet, avoid using double quoted string literals after the attribute 'width', because the excel sheet won't display the table.  
Example:
<?php
header("Content-Type:  application/vnd.ms-excel");
echo "<table border=1 align=center width=95\"%\">";
echo "<table>";
echo "<tr><td>abc</td><tr>";
echo "<tr><td>xyz</td><tr>";
echo "</table>";
?>
Use "<table border=1 align=center width=95%>" instead.


www.feisar.de

watch out when comparing strings that are numbers. this example:
<?php
$x1 = '111111111111111111';
$x2 = '111111111111111112';
echo ($x1 == $x2) ? "true\n" : "false\n";
?>
will output "true", although the strings are different. With large integer-strings, it seems that PHP compares only the integer values, not the strings. Even strval() will not work here.
To be on the safe side, use:
$x1 === $x2


webmaster

Use caution when you need white space at the end of a heredoc. Not only is the mandatory final newline before the terminating symbol stripped, but an immediately preceding newline or space character is also stripped.
For example, in the following, the final space character (indicated by \s -- that is, the "\s" is not literally in the text, but is only used to indicate the space character) is stripped:
$string = <<<EOT
this is a string with a terminating space\s
EOT;
In the following, there will only be a single newline at the end of the string, even though two are shown in the text:
$string = <<<EOT
this is a string that must be
followed by a single newline
EOT;


richard neill

Unlike bash, we can't do
 echo "\a"       #beep!
Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:  echo "\x07"


bluej100@gmail

This is debatably a bug, and certainly not what I expected:
<?php
var_dump('00' == '0e99'); // true
var_dump('0e99' == '00'); // true
?>
Basically, any two strings such that each matches /0+([eE]\d+)?/ are equal.


thomas dot oldbury dot nospam

This function I created to insert a string at a position or an array of positions. Quite useful.
<?php
/*

string strwpos (string insert, string input, int position [, int mode])

Returns a string with a string inserted at a position,
or an array of positions. Normally, the string is inserted
on the right of the position, but it can be inserted on the
left or both. The following constants define where the string
should be inserted:

INS_LEFT  -  insert the string left of the position
INS_RIGHT - insert the string right of the position
INS_BOTH  -  insert the string on both sides

Returns resulting string on success, FALSE on failure.

*/
define('INS_LEFT', 0);
define('INS_RIGHT', 1);
define('INS_BOTH', 2);
function strwpos($ins, $string, $pos, $mode = INS_RIGHT)
{
$str = "";

for($c = 0; $c < strlen($string); $c++)
{
if(is_array($pos))
{
if(in_array($c, $pos, true))
{
if($mode == INS_RIGHT)
{
$ins_c = substr($string, $c, 1) . $ins;
}
elseif($mode == INS_LEFT)
{
$ins_c = $ins . substr($string, $c, 1);
}
elseif($mode == INS_BOTH)
{
$ins_c = $ins . substr($string, $c, 1) . $ins;
}
else
{
trigger_error("Unknown mode '$mode' specified", E_USER_WARNING);
return false;
}
$str .= $ins_c;
}
else
{
$str .= $string[$c];
}
}
else
{
if($c == $pos)
{
if($mode == INS_RIGHT)
{
$ins_c = substr($string, $c, 1) . $ins;
}
elseif($mode == INS_LEFT)
{
$ins_c = $ins . substr($string, $c, 1);
}
elseif($mode == INS_BOTH)
{
$ins_c = $ins . substr($string, $c, 1) . $ins;
}
else
{
trigger_error("Unknown mode '$mode' specified", E_USER_WARNING);
return false;
}
$str .= $ins_c;
}
else
{
$str .= $string[$c];
}
}
}

return $str;
}
?>
This function can have a few problems. For example, the following code will produce an unexpected result:
<?php echo strwpos('love, not ', 'I hate you', 2); ?>
It will produce this result:
  I hlove, not ate you
The reason for this is because the string is inserted to the right of the string by default. So using the optional MODE parameter with the INS_LEFT value will produce the result we need.
<?php echo strwpos('love, not ', 'I hate you', 2, INS_LEFT); ?>
This will produce the result we need:
  I love, not hate you
You can also use an array of places to insert the string into:
<?php echo strwpos('brown ', 'The quick fox jumped over the lazy dog', array(10, 35), INS_LEFT); ?>
This will produce the result:
  The quick brown fox jumped over the lazy brown dog
Hope this helps.


php

The section `#language.types.string.parsing' above says:
"Before PHP 5.1.1, backslash in \{$var} hasn't been printed."
...but does not inform how to fix that. The answer is easy: double each curly-bracket.
So, when producing inline CSS:
<?php
$hBack = '#99ccff';
$hFore = '#000088';
$style = "background:$hBack;color:$hFore;"
echo "h1 {background:$hBack;color:$hFore;}
h2 \{$style}
h3 {{$style}}";
?>
PHP < v5.1.1 prints:
h1 {background:#99ccff;color:#000088;}
h2 {background:#99ccff;color:#000088;}
h3 {background:#99ccff;color:#000088;}
PHP => v5.1.1 prints:
h1 {background:#99ccff;color:#000088;}
h2 \{background:#99ccff;color:#000088;}
h3 {background:#99ccff;color:#000088;}
Please note: I have not checked `{{$style}}' on PHP before v5.1.1; the assumption seems reasonable.


bluej100@gmail

The '0e00' == '00' scientific notation strangeness is documented at http://us2.php.net/manual/en/language.operators.comparison.php:
"If you compare two numerical strings, they are compared as integers."
I don't see any documentation for the odd handling of hexadecimal strings, though.
var_dump(intval('0xf')) // int(0)
var_dump((int)'0xf') // int(0)
var_dump(0 + '0xf') // int(15)
var_dump('0xf' == 15) // bool(true)


03-mar-2003 06:04

Regarding "String access by character":
Apparently if you edit a specific character in a string, causing the string to be non-continuous, blank spaces will be added in the empty spots.
echo '<pre>';
$str = '0123';
echo "$str\n";
$str[4] = '4';
echo "$str\n";
$str[6] = '6';
echo "$str\n";
This will output:
0123
01234
01234 6
Notice the blank space where 5 should be.


guidod

PHP's double-quoted strings are inherently ill-featured - they will be a problem especially with computed code like in /e-evals with preg_replace.
bash and perl follow the widely accepted rule that all backslashes will escape the nextfollowing char, and nonalpha-chars will always get printed there as themselves whereas (the unescaped chars might have special meaning in regex). Anyway, it is a great way to just escape all nonalpha chars that you uncertain about whether they have special meaning in some places, and ye'll be sure they will get printed literal.
Furthermore, note that \{ sequence is not mentioned in the  escape-char table! You'll get to know about it only "complex (curly) syntax". This can even more be a problem with evals, as they behave rather flaky like it _cannot_ be accomodated for computed code. Try all variants of `echo "hello \{\$world}"` removing one or more of the chars in the \{\$ part - have fun!


philip

Note that in PHP versions 4.3.0 and 4.3.1, the following provides a bogus E_NOTICE (this is a known bug):
echo "$somearray['bar']";
This is accessing an array inside a string using a quoted key and no {braces}.  Reading the documention shows all the correct ways to do this but the above will output nothing on most systems (most have E_NOTICE off) so users may be confused.  In PHP 4.3.2, the above will again yield a parse error.


csaba

Multiline strings:
In most of the strings on this doc page, the heredoc form (<<<) is not needed.  The heredoc form is useful when you also want to embed, without escaping, quotes of the same type as the starting quote.  The single quote form is particularly useful when you want to specify multiline code for future evaluation.
<?php
$code = '
 $output = "Mutliline output";
 $out = "$output within multiline code:
$ needs escaping within \$out,
and double quotes (\") need escaping within \$out,
but single quotes (\') need escaping everywhere.";
 // Next two lines work with php.exe
 /* on Windows systems */
 $oWSH = new COM("WScript.Shell");
 $oWSH->Popup($out, 4, \'IO Demo\', 131120);
';
print "<pre>$code</pre>";
call_user_func (create_function('', $code));
?>
Happy New Year,
Csaba Gabor from Vienna


frosty

mouse:
test_double_quote_replace was only faster because it was $a was all contained in a single set of quotes.


deletethis dot php

Just some quick observations on variable interpolation:
Because PHP looks for {? to start a complex variable expression in a double-quoted string, you can call object methods, but not class methods or unbound functions.
This works:
<?php
class a {
   function b() {
       return "World";
   }
}
$c = new a;
echo "Hello {$c->b()}.\n"
?>
While this does not:
<?php
function b() {
   return "World";
}
echo "Hello {b()}\n";
?>
Also, it appears that you can almost without limitation perform other processing within the argument list, but not outside it.  For example:
<?
$true = true;
define("HW", "Hello World");
echo "{$true && HW}";
?>
gives: Parse error: parse error, unexpected T_BOOLEAN_AND, expecting '}' in - on line 3
There may still be some way to kludge the syntax to allow constants and unbound function calls inside a double-quoted string, but it isn't readily apparent to me at the moment, and I'm not sure I'd prefer the workaround over breaking out of the string at this point.


fmouse

It may be obvious to some, but it's convenient to note that variables _will_ be expanded inside of single quotes if these occur inside of a double-quoted string.  This can be handy in constructing exec calls with complex data to be passed to other programs.  e.g.:
$foo = "green";
echo "the grass is $foo";
the grass is green
echo 'the grass is $foo';
the grass is $foo
echo "the grass is '$foo'";
the grass is 'green'


rkfranklin+php

If you want to use a variable in an array index within a double quoted string you have to realize that when you put the curly braces around the array, everything inside the curly braces gets evaluated as if it were outside a string.  Here are some examples:
<?php
$i = 0;
$myArray[Person0] = Bob;
$myArray[Person1] = George;
// prints Bob (the ++ is used to emphasize that the expression inside the {} is really being evaluated.)
echo "{$myArray['Person'.$i++]}
";
// these print George
echo "{$myArray['Person'.$i]}
";
echo "{$myArray["Person{$i}"]}
";
// These don't work
echo "{$myArray['Person$i']}
";
echo "{$myArray['Person'$i]}
";
// These both throw fatal errors
// echo "$myArray[Person$i]
";
//echo "$myArray[Person{$i}]
";
?>


adam

If you really want to get constants inside your string you can do something like this (PHP5 only).
<?php
class GetConstant {
public function __get($constant_name) {
 return (defined($constant_name) ? constant($constant_name) : NULL);
}
}
$C = new GetConstant();
define('FOO','bar');
echo("I want a candy {$C->FOO}.");
?>


mouse

I'm used the following code:
<?php
function test_simple_quote_concat()
{
 $b = 'string';
 $a  = ' string'.$b.' string'.$b.' srting'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
}
function test_double_quote_concat()
{
 $b = "string";
 $a  = " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
}
function test_double_quote_replace()
{
 $b = "string";
 $a = " string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b";
}
function test_eot_replace()
{
 $b = <<<EOT
string
EOT;
 $a = <<<EOT
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
EOT;
}
$iter = 100000;
$time_start = microtime(1);
$time_start = microtime(1);
for( $i=0; $i<$iter; $i++ )
 test_double_quote_concat();
$duration2 = microtime(1) - $time_start;
$time_start = microtime(1);
for( $i=0; $i<$iter; $i++ )
 test_double_quote_replace();
$duration3 = microtime(1) - $time_start;
$time_start = microtime(1);
for( $i=0; $i<$iter; $i++ )
 test_eot_replace();
$duration4 = microtime(1) - $time_start;
$time_start = microtime(1);
for( $i=0; $i<$iter; $i++ )
 test_simple_quote_concat();
$duration1 = microtime(1) - $time_start;
echo 'simple_quote_concat: '.$duration1." s\n";
echo 'double_quote_concat: '.$duration2." s\n";
echo 'double_quote_replace: '.$duration3." s\n";
echo 'eot_quote_replace: '.$duration4." s\n";
?>
And got very different results. Compare it yourself.
$ php test.php
simple_quote_concat: 0.853082895279 s
double_quote_concat: 0.896748065948 s
double_quote_replace: 0.708463907242 s
eot_quote_replace: 0.735204935074 s
$ php test.php
simple_quote_concat: 0.786070823669 s
double_quote_concat: 0.800376176834 s
double_quote_replace: 0.659599065781 s
eot_quote_replace: 0.674590110779 s
$ php test.php
simple_quote_concat: 0.819690942764 s
double_quote_concat: 0.842829942703 s
double_quote_replace: 0.659816980362 s
eot_quote_replace: 0.756074905396 s
$ php test.php
simple_quote_concat: 0.785160064697 s
double_quote_concat: 0.77215385437 s
double_quote_replace: 0.659204006195 s
eot_quote_replace: 0.67343211174 s
As you can see, simple and double quoted strings very close to each other.


maikel7

I was curious about speed differences between "some text $var" and "some text".$var. And my tests seem to be quite the opposite to the benchmarks posted below by "php at moechofe dot com". I used this code:
<?php
function microtime_float() {
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}
$str = "some text";
$time_start = microtime_float();
for ($i=0; $i<100000; $i++) {
$a="x $str o $str a $str d $str f $str";
}
$duration1 = microtime_float() - $time_start;
$time_start = microtime_float();
for ($i=0; $i<100000; $i++) {
$a="x ".$str." o ".$str." a ".$str." d ".$str." f ".$str;
}
$duration2 = microtime_float() - $time_start;
?>
On a windows machine $duration1 is about 2.5x greater (=slower) than $duration2. I ran it also on several hosting servers (Linux-based) and the differnces were smaller but still $duration1 was much greater. Only on one of the hosts where they use eAccellarator there was no difference between the two methods. So my conclusion is not to use "$variables in double-quoted strings" wherever speed is important.


topnotcher

I have come across this several times, and as far as I can tell, the < and > operators have undocumented functionality when it comes to comparing strings.  Consider the following script:
<?php
$a = '2007-11-05 15:17:49';
$b = '2007-11-05 15:17:48';
$bool = $a > $b;
var_dump($bool); //bool(true)
/**
* The manual tells us that $a and $b should be
* truncated at -, thus giving a floating-point value of 2007.
* But (2007 > 2007) === false...
*/
$a = (float)$a;
$b = (float)$b;
var_dump($a); //float(2007);
var_dump($b); //float(2007);
/**
* And the manual is right. So why does it correctly
* compare the dates (which should be treated
* as normal strings? Clearly some hidden functionality...
*/


michael

Heredocs can be used for more than just echoing or setting variables - use them whenever you want to include a string.
function header() {
 return <<<EOT
   <html>
     <head>
       <title>This is my heredoc</title>
     </head>
     <body>
EOT;
Also, note the strict syntax:
- No semicolon after initial EOT (think of the heredoc as a literal string arg - you wouldn't want a semicolon in front of it, would you?)
- BUT need semicolon after final EOT (the command is finished here)
- Final EOT is on the left margin - don't indent it!


atnak

Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:
$string = 'a';
var_dump($string[2]);  // string(0) ""
var_dump($string[7]);  // string(0) ""
$string[7] === '';  // TRUE
It appears that anything past the end of the string gives an empty string..  However, when E_NOTICE is on, the above examples will throw the message:
Notice:  Uninitialized string offset:  N in FILE on line LINE
This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.
isset($string[7]);  // FALSE
$string[7] === NULL;  // FALSE
Even though it seems like a not-NULL value of type string, it is still considered unset.


php

Function calls within double-quote variable interpolation work in PHP 5, but not quite as you'd expect. Basically the function has to be a variable function. I.e. a variable that holds the name of a function. So if you've got a function named 'x' that you want to call, you'll have to assign the function name to a variable. It's easiest to just assign it to a variable with the same name:
function x () { return 4; }
$x = 'x';
echo "x = {$x()}";
I'm not sure what the point of that is though, since it would be easier to do it this way:
function x () { return 4; }
$x = x();
echo "x = $x";


ktcb123

For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.
<?php
function url_exists($url){
$url = str_replace("http://", "", $url);
if (strstr($url, "/")) {
$url = explode("/", $url, 2);
$url[1] = "/".$url[1];
} else {
$url = array($url, "/");
}
$fh = fsockopen($url[0], 80);
if ($fh) {
fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$url[0]."\n\n");
if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
else { return TRUE; }
} else { return FALSE;}
}
?>


vallo

Even if the correct way to handle variables is determined from the context, some things just doesn't work without doing some preparation.
I spent several hours figuring out why I couldn't index a character out of a string after doing some math with it just before. The reason was that PHP thought the string was an integer!
$reference = $base + $userid;
.. looping commands ..
$chartohandle = $reference{$last_char - $i};
Above doesn't work. Reason: last operation with $reference is to store a product of an addition -> integer variable. $reference .=""; (string catenation) had to be added before I got it to work:
$reference = $base + $userid;
$reference .= "";
.. looping commands ..
$chartohandle = $reference{$last_char - $i};
Et voilá! Nice stream of single characters.


penda ekoka

error control operator (@) with heredoc syntax:
the error control operator is pretty handy for supressing minimal errors or omissions. For example an email form that request some basic non mandatory information to your users. Some may complete the form, other may not. Lets say you don't want to tweak PHP for error levels and you just wish to create some basic template that will be emailed to the admin with the user information submitted. You manage to collect the user input in an array called $form:
<?php
// creating your mailer
$mailer = new SomeMailerLib();
$mailer->from = ' System <mail@yourwebsite.com>';
$mailer->to = 'admin@yourwebsite.com';
$mailer->subject = 'New user request';
// you put the error control operator before the heredoc operator to suppress notices and warnings about unset indices like this
$mailer->body = @<<<FORM
Firstname = {$form['firstname']}
Lastname = {$form['lastname']}
Email = {$form['email']}
Telephone = {$form['telephone']}
Address = {$form['address']}
FORM;
?>


og

easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');
$const = get_defined_constants();
echo <<<END
{$const['TEST']}
END;
Result:
TEST STRING


dandrake

By the way, the example with the "\n" sequence will insert a new line in the html code, while the output will be decided by the HTML syntax. That's why, if you use
<?
echo "Hello \n World";
?>
the browser will receive the HTML code on 2 lines
but his output on the page will be shown on one line only.
To diplay on 2 lines simply use:
<?
echo "Hello
World";
?>
like in HTML.


bryant

As of (at least) PHP 5.2, you can no longer convert an object to a string unless it has a __toString method. Converting an object without this method now gives the error:
PHP Catchable fatal error:  Object of class <classname> could not be converted to string in <file> on line <line>
Try this code to get the same results as before:
<?php
if (!is_object($value) || method_exists($value, '__toString')) {
   $string = (string)$value;
} else {
   $string = 'Object';
}
?>


php

A simple benchmark to check differents about :
- simple and double quote concatenation and
- double quote and heredoc replacement
<?php
function test_simple_quote_concat()
{
 $b = 'string';
 $a  = ' string'.$b.' string'.$b.' srting'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
 $a .= ' string'.$b.' string'.$b.' string'.$b;
}
function test_double_quote_concat()
{
 $b = "string";
 $a  = " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
 $a .= " string".$b." string".$b." string".$b;
}
function test_double_quote_replace()
{
 $b = "string";
 $a = " string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b";
}
function test_eot_replace()
{
 $b = <<<EOT
string
EOT;
 $a = <<<EOT
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
EOT;
}
$iter = 2000;
for( $i=0; $i<$iter; $i++ )
 test_simple_quote_concat();
for( $i=0; $i<$iter; $i++ )
 test_double_quote_concat();
for( $i=0; $i<$iter; $i++ )
 test_double_quote_replace();
for( $i=0; $i<$iter; $i++ )
 test_eot_replace();
?>
I've use xdebug profiler to obtain the followed results:
test_simple_quote_concat : 173ms
test_double_quote_concat : 161ms
test_double_quote_replace : 147ms
test_eot_replace : 130ms


jonathan lozinski

A note on the heredoc stuff.
If you're editing with VI/VIM and possible other syntax highlighting editors, then using certain words is the way forward.  if you use <<<HTML for example, then the text will be hightlighted for HTML!!
I just found this out and used sed to alter all EOF to HTML.
JAVASCRIPT also works, and possibly others.  The only thing about <<<JAVASCRIPT is that you can't add the <script> tags..,  so use HTML instead, which will correctly highlight all JavaScript too..
You can also use EOHTML, EOSQL, and EOJAVASCRIPT.


philip

A nice "Introduction to PHP Strings" tutorial:
 http://www.zend.com/zend/tut/using-strings.php


Change Language


Follow Navioo On Twitter
Introduction
Booleans
Integers
Floating point numbers
Strings
Arrays
Objects
Resource
NULL
Pseudo-types and variables used in this documentation
Type Juggling
eXTReMe Tracker