PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

配列> <浮動小数点数
Last updated: Fri, 10 Oct 2008

view this page in

文字列

string は、文字が連結されたものです。PHP では、 文字は 1 バイトと同じです。つまり、256 個の異なる文字を使用可能です。 これは、PHP が Unicode をネイティブにサポートしていないことも意味します。 いくつかの Unicode サポートについてはutf8_encode() および utf8_decode() を参照してください。

注意: 文字列が非常に大きくなっても問題ありません。 PHP に課せられる文字列のサイズの実用上の制限はありません。 このため、長い文字列に関して恐れる必要は全くありません。

構文

文字列リテラルは、4 つの異なる方法で指定することが可能です。

引用符

文字列を指定する最も簡単な方法は、引用符 (文字 ') で括ることです。

引用符をリテラルとして指定するには、多くの他の言語と同様にバックスラッシュ (\) でエスケープする必要があります。 バックスラッシュを引用符の前または文字列の最後に置きたい場合は、 二重にする必要があります。この他の文字をエスケープする場合には、 バックスラッシュも出力されることに注意してください! このため、 通常はバックスラッシュ自体をエスケープする必要はありません。

注意: 他の二つの構文と異なり、 変数と特殊文字のエスケープシーケンスは、 引用符 (シングルクオート) で括られた文字列にある場合には展開されません

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

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

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

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

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

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

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

二重引用符

文字列が二重引用符 (") で括られた場合、 PHP は、より多くの特殊文字のエスケープシーケンスを理解します。

エスケープされた文字
記述 意味
\n ラインフィード (LF またはアスキーの 0x0A (10))
\r キャリッジリターン (CR またはアスキーの 0x0D (13))
\t 水平タブ (HT またはアスキーの 0x09 (9))
\v 垂直タブ (VT またはアスキーの 0x0B (11)) (PHP 5.2.5 以降)
\f フォームフィード (FF またはアスキーの 0x0C (12)) (PHP 5.2.5 以降)
\\ バックスラッシュ
\$ ドル記号
\" 二重引用符
\[0-7]{1,3} 正規表現にマッチする文字シーケンスは、8 進数表記の 1 文字です。
\x[0-9A-Fa-f]{1,2} 正規表現にマッチする文字シーケンスは、16 進数表記の 1 文字です。

繰り返しますが、この他の文字をエスケープしようとした場合には、 バックスラッシュも出力されます! PHP 5.1.1 より前のバージョンでは、\{$var} のバックスラッシュは出力されません。

しかし、二重引用符で括られた文字列で最も重要なのは、 変数名が展開されるところです。詳細は、文字列のパースを参照ください。

ヒアドキュメント

文字列を区切る別の方法としてヒアドキュメント構文 ("<<<") があります。この場合、ある ID (と、それに続けて改行文字) を <<< の後に指定し、文字列を置いた後で、同じ ID を括りを閉じるために置きます。

終端 ID は、その行の最初のカラムから始める必要があります。 使用するラベルは、PHP の他のラベルと同様の命名規則に従う必要があります。 つまり、英数字およびアンダースコアのみを含み、 数字でない文字またはアンダースコアで始まる必要があります。

警告

非常に重要なことですが、終端 ID がある行には、セミコロン (;) 以外の他の文字が含まれていてはならないことに注意しましょう。 これは、特に ID はインデントしてはならないということ、 セミコロンの前に空白やタブを付けてはいけないことを意味します。 終端 ID の前の最初の文字は、使用するオペレーティングシステムで定義された 改行である必要があることにも注意を要します。 これは、例えば、Macintoshでは \r となります。 最後の区切り文字 (たいていはその後にセミコロンが続きます) の後にもまた、改行を入れる必要があります。

この規則が破られて終端 ID が "clean" でない場合、 終端 ID と認識されず、PHP はさらに終端 ID を探し続けます。 適当な終了 ID がみつからない場合、 スクリプトの最終行でパースエラーが発生します。

ヒアドキュメント構文を、クラスのメンバの初期化に用いることはできません。 nowdoc を使用しましょう。

例1 間違った例

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

ヒアドキュメントは二重引用符を使用しませんが、 二重引用符で括られた文字列と全く同様に動作します。 しかし、この場合でも上記のリストでエスケープされたコードを使用することも可能です。 変数は展開されますが、文字列の場合と同様に ヒアドキュメントの内部で複雑な変数を表わす場合には注意が必要です。

例2 ヒアドキュメントで文字列を括る例

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

/* 変数を使用するより複雑な例 */
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;
?>

上の例の出力は以下となります。

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

ヒアドキュメント構文を用いて、 関数の引数にデータを渡すこともできます。

例3 ヒアドキュメントを引数に使用する例

<?php
var_dump
(array(<<<EOD
foobar!
EOD
));
?>

注意: ヒアドキュメントは PHP 4 で追加されました。

Nowdoc

Nowdoc はヒアドキュメントと似ていますが、 ヒアドキュメントがダブルクォートで囲んだ文字列として扱われるのに対して、 Nowdoc はシングルクォートで囲んだ文字列として扱われます。 Nowdoc の使用方法はヒアドキュメントとほぼ同じですが、 その中身について パース処理を行いません。 PHP のコードや大量のテキストを埋め込む際に、 エスケープが不要になるので便利です。この機能は、SGML の <![CDATA[ ]]> (ブロック内のテキストをパースしないことを宣言する) と同じようなものです。

Nowdoc の書き方は、ヒアドキュメントと同じように <<< を使用します。 しかし、その後に続く識別子をシングルクォートで囲んで <<<'EOT' のようにします。 ヒアドキュメントの識別子に関する決まりがすべて Nowdoc の識別子にも当てはまります。特に終了識別子の書き方に関する決まりに注意しましょう。

例4 Nowdoc による文字列のクォートの例

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

/* 変数を使った、より複雑な例 */
class foo
{
    public 
$foo;
    public 
$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.
NowI am printing some {$foo->bar[1]}.
This should not print a capital 'A'x41
EOT
;
?>

上の例の出力は以下となります。

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

注意: ヒアドキュメントと異なり、Nowdoc は任意の静的データコンテキストで使用できます。 典型的な使用例は、クラスのメンバーや定数の初期化です。

例5 静的データの例

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

注意: Nowdoc のサポートは PHP 5.3.0 で追加されました。

変数のパース

スクリプトが二重引用符で括られるかヒアドキュメントで指定された場合、 その中の変数はパースされます。

構文の型には、単純な構文と 複雑な 構文の 2 種類があります。簡単な構文は、最も一般的で便利です。 この構文では、変数、配列値やオブジェクトのプロパティをパースすることが可能です。

複雑な構文は、PHP 4 で導入されました。 この構文は、式を波括弧で括ることにより認識されます。

簡単な構文

ドル記号 ($) を見付けると、 パーサは、有効な変数名を形成することが可能な最長のトークンを取得します。 変数名の終りを明示的に指定したい場合は、変数名を波括弧で括ってください。

<?php
$beer 
'Heineken';
echo 
"$beer's taste is great"// 動作します。"'" は変数名として無効な文字です。
echo "He drunk some $beers";   // 動作しません。's' は、変数名として有効な文字ですが、実際の変数名は "$beer" です。
echo "He drunk some ${beer}s"// 動作します。
echo "He drank some {$beer}s"// 動作します。
?>

同様に、配列添字とオブジェクトのプロパティをパースすることも可能です。 配列添字の場合、閉じ角括弧 (']') は添字の終りを意味し、 オブジェクトのプロパティの場合、同じ規則が簡単な変数として適用されます。 しかし、オブジェクトプロパティには、変数の場合のような手法はありません。

<?php
// これらの例は、文字列の内部で配列を使用する際のものです。
// 文字列の外部で使用する場合は、配列の文字列キーは常にクオート
// しましょう。また、{波括弧} も使用しないようにしましょう。

// すべてのエラーを表示するようにします。
error_reporting(E_ALL);

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

// シングルクオートの外では動作が異なることに注意してください。
echo "A banana is $fruits[banana].";

// 動作します。
echo "A banana is {$fruits['banana']}.";

// 動作しますが、以下に説明するように
// PHP はまず banana という名前の定数を探します。
echo "A banana is {$fruits[banana]}.";

// 動作しません。波括弧を使用しましょう。これはパースエラーとなります。
echo "A banana is $fruits['banana'].";

// 動作します。
echo "A banana is " $fruits['banana'] . ".";

// 動作します。
echo "This square is $square->width meters broad.";

// 動作しません。解決策については、複雑な構文を参照ください。
echo "This square is $square->width00 centimeters broad.";
?>

より複雑な場合は、複雑な構文を使用する必要があります。

複雑な (波括弧) 構文

この構文が「複雑(complex)な構文」と呼ばれているのは、 構文が複雑であるからではなく、 この方法では複雑な式を含めることができるからです。

事実、この構文により、文字列の中に名前空間内のあらゆる値を含めることが可能です。 文字列の外側に置く場合と同様に式を書き、これを { と } の間に含めてください。'{' はエスケープすることができないため、 この構文は $ が { のすぐ後に続く場合にのみ認識されます (リテラル "{$" を指定するには、"{\$" を使用してください)。 以下のいくつかの例を見ると理解しやすくなるでしょう。

<?php
// すべてのエラーを表示します
error_reporting(E_ALL);

$great 'fantastic';

// うまく動作しません。出力: This is { fantastic}
echo "This is { $great}";

// うまく動作します。出力: This is fantastic
echo "This is {$great}";
echo 
"This is ${great}";

// 動作します
echo "This square is {$square->width}00 centimeters broad."

// 動作します
echo "This works: {$arr[4][3]}";

// これが動作しない理由は、文字列の外で $foo[bar]
// が動作しない理由と同じです。
// 言い換えると、これは動作するともいえます。しかし、
// PHP はまず最初に foo という名前の定数を探すため、
// E_NOTICE レベルのエラー(未定義の定数) となります。
echo "This is wrong: {$arr[foo][3]}"

// 動作します。多次元配列を使用する際は、
// 文字列の中では必ず配列を波括弧で囲むようにします。
echo "This works: {$arr['foo'][3]}";

// 動作します
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}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

注意: {$ } の内部における 関数やメソッドのコールは、PHP 5 から動作します。

注意: 文字列内での変数のパースは、文字列の連結に比べてよりメモリを消費します。 メモリの使用量をできるだけ抑えた PHP スクリプトを書きたいのなら、 変数のパースを用いるのではなく、連結演算子 (.) を使用しましょう。

文字列への文字単位のアクセスと修正

$str[42] のように、 角括弧を使用してゼロから始まるオフセットを指定すると、 文字列内の任意の文字にアクセスし、修正することが可能です。 つまり、文字列を文字の配列として考えるわけです。 波括弧の後に任意の文字をゼロから始まるオフセットで指定することにより、 文字列内の文字にアクセス/修正することが可能です。

注意: $str{42} のように波括弧を使用してアクセスすることも可能です。 しかし、角括弧を使用する方法のほうが推奨されます。 なぜなら、{波括弧} 形式は PHP 6 で廃止される予定だからです。

例6 文字列の例

<?php
// 文字列の最初の文字を取得します
$str 'This is a test.';
$first $str[0];

// 文字列の 3 番目の文字を取得します
$third $str[2];

// 文字列の最後の文字を取得します
$str 'This is still a test.';
$last $str[strlen($str)-1]; 

// 文字列の最後の文字を変更します
$str 'Look at the sea';
$str[strlen($str)-1] = 'e';

// {} を使用した、もうひとつの方法 (PHP 6 で廃止予定) です
$third $str{2};

?>

注意: その他の型の変数に対して []{} でアクセスすると、何もメッセージを出さずに単に NULL を返します。

便利な関数および演算子

文字列は、'.' (ドット) 結合演算子で結合することが可能です。'+' (加算) 演算子はこの例では出てこないことに注意してください。詳細については 文字列演算子 を参照ください。

文字列の修正を行う場合には、便利な関数がたくさん用意されています。

一般的な関数については、文字列関数の節 を参照ください。高度な検索/置換を行う正規表現関数については Perl および POSIX 拡張 の 2 種類がありますが、 それぞれの節を参照ください。

URL 文字列用関数や文字列の暗号化/ 復号用の関数 (mcrypt および mhash) もあります。

最後に、探しているものがまだ見付からない場合には、 文字型の関数も参照ください。

文字列への変換

(string) キャストや strval() 関数を使って変数を文字列へ変換することができます。 文字列型を必要とする式のスコープにおいて、文字列への変換は自動的に行われます。 echo()print() 関数を使うとき、 あるいは可変変数を文字列を比較するときにこの自動変換が行われます。 マニュアルの型の相互変換 の項を読むとわかりやすいでしょう。 settype()も参照してください。

booleanTRUE は文字列の "1" に、 FALSE"" (空文字列) に変換されます。 これにより boolean と文字列の値を相互に変換することができます。

integer (整数) や浮動小数点数 (float) は その数値の数字として文字列に変換されます (指数の表記や浮動小数点数を含めて)。 浮動小数点数は、指数表記 (4.1E+6) を使用して変換されます。

注意: 小数点を表す文字は、スクリプトのロケール (LC_NUMERIC カテゴリ) によって決まります。 setlocale() を参照ください。

配列は常に "Array" という文字列に変換されるので、 array の中を見るために echo()print() を使ってダンプさせることはできません。 一つの要素を見るためには、echo $arr['foo'] のようにしてください。内容の全てをダンプ/見るためには以降の TIP をご覧ください。

PHP 4 のオブジェクトは、常に "Object" という文字列に変換されます。 デバッグ等のために object の内部の変数を出力するような場合には、 以下をご覧ください。オブジェクトがなんという名前のクラスの インスタンスなのかを知るには get_class() をご覧ください。 PHP 5 以降では、もし存在すれば __toString() メソッドを使用します。

リソースは常に "Resource id #1" という文字列に変換されます。1 は実行中の PHP によって割り当てられる resource のユニークな番号です。 リソースの型を知るためには get_resource_type() を使用してください。

NULL は常に空文字列に変換されます。

以上に述べたように、配列、オブジェクト、リソースをプリントアウトしても その値に関する有益な情報を得られるわけではありません。 デバッグのために値を出力するのによりよい方法が知りたければ、 print_r()var_dump() を参照ください。

PHP 変数を恒久的に保存するための文字列に変換することもできます。 この方法はシリアライゼーションと呼ばれ、 serialize() 関数によって実現できます。 WDDX サポートを有効にして PHP をセットアップすれば、PHP 変数を XML 構造にシリアライズすることもできます。

文字列の数値への変換

数値として文字列が評価された時、結果の値と型は次のように定義されます。

文字列は、'.'、'e'、'E' のどれかが含まれている場合は float、それ以外は整数として評価されます。

文字列の最初の部分により値が決まります。文字列が、 有効な数値データから始まる場合、この値が使用されます。その他の場合、 値は 0 (ゼロ) となります。有効な数値データは符号(オプション)の後に、 1 つ以上の数字 (オプションとして小数点を 1 つ含む)、 オプションとして指数部が続きます。指数部は 'e' または 'E' の後に 1 つ以上の数字が続く形式です。

<?php
$foo 
"10.5";              // $foo は float です (11.5)
$foo "-1.3e3";            // $foo は float です (-1299)
$foo "bob-1.3e3";         // $foo は integer です (1)
$foo "bob3";              // $foo は integer です (1)
$foo "10 Small Pigs";     // $foo は integer です (11)
$foo "10 Little Piggies"// $foo は integer です (11)
$foo "10.0 pigs " 1;        // $foo は integer です (11)
$foo "10.0 pigs " 1.0;      // $foo は float です (11)
?>

この変換に関する詳細は、Unix のマニュアルページで strtod(3) を参照ください。

本節の例を試したい場合、その例をカットアンドペーストしてから 動作を確認するために次の行を挿入してください。

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

(C 言語で行われるように) 数値に変換することで 一つの文字のコードを取得できると期待してはいけません。 文字と文字コードを相互に変換するには ord() および chr() 関数を使用してください。



配列> <浮動小数点数
Last updated: Fri, 10 Oct 2008
 
add a note add a note User Contributed Notes
文字列
steve at mrclay dot org
30-Sep-2008 10:33
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

<?php
function doubleQuote($str) {
   
$ret = '"';
    for (
$i = 0, $l = strlen($str); $i < $l; ++$i) {
       
$o = ord($str[$i]);
        if (
$o < 31 || $o > 126) {
            switch (
$o) {
                case
9: $ret .= '\t'; break;
                case
10: $ret .= '\n'; break;
                case
11: $ret .= '\v'; break;
                case
12: $ret .= '\f'; break;
                case
13: $ret .= '\r'; break;
                default:
$ret .= '\x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
            }
        } else {
            switch (
$o) {
                case
36: $ret .= '\$'; break;
                case
34: $ret .= '\"'; break;
                case
92: $ret .= '\\\\'; break;
                default:
$ret .= $str[$i];
            }
        }
    }
    return
$ret . '"';
}
?>
chAlx at findme dot if dot u dot need
11-Sep-2008 05:42
To save Your mind don't read previous comments about dates  ;)

When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:

<?php
var_dump
('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
harmor
02-Sep-2008 12:05
So you want to get the last character of a string using "String access and modification by character"?  Well negative indexes are not allowed so $str[-1] will return an empty string.

<?php
//Tested using: PHP 5.2.5

$str = 'This is a test.';

$last = $str[-1];                  //string(0) ""
$realLast = $str[strlen($str)-1];  //string(1) "."
$substr = substr($str,-1);         //string(1) "."

echo '<pre>';
var_dump($last);
var_dump($realLast);
var_dump($substr);
nullhility at gmail dot com
06-Jun-2008 09:40
It's also valuable to note the following:

<?php
${date("M")} = "Worked";
echo ${
date("M")};
?>

This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo statement. Have fun ;).
sk89q
30-Apr-2008 09:46
<?php
$F
= "F";
function
F($s) { return $s; }
$filename = '<some code>';
echo
"{$F(htmlspecialchars($filename))}";
?>
yuku
01-Apr-2008 04:21
This example of the heredoc has wrong output:
Code: This should print a capital 'A': \x41
Output should be: This should print a capital 'A': A

The example of the nowdoc has wrong code:
Code: This should not print a capital 'A': x41
That should be: This should not print a capital 'A': \x41
chris at chrisstockton dot org
24-Mar-2008 03:58
For anyone who reads Evan K, please note that:
// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);

Is identical to (note all I added was a backslash before $):
$before = "Quantity:\t500\nPrice:\t\$5.25 each";
var_dump($before);

So its definitely better to escape a dollar instead of all the overhead of his regex and evals and such, although clever completely unnecessary.

-Chris
Evan K
28-Feb-2008 10:03
I encountered the odd situation of having a string containing unexpanded escape sequences that I wanted to expand, but also contained dollar signs that would be interpolated as variables.  "$5.25\n", for example, where I want to convert \n to a newline, but don't want attempted interpolation of $5.

Some muddling through docs and many obscenties later, I produced the following, which expands escape sequences in an existing string with NO interpolation.

<?php

// where we do all our magic
function expand_escape($string) {
    return
preg_replace_callback(
       
'/\\\([nrtvf]|[0-7]{1,3}|[0-9A-Fa-f]{1,2})?/',
       
create_function(
           
'$matches',
           
'return ($matches[0] == "\\\\") ? "" : eval( sprintf(\'return "%s";\', $matches[0]) );'
       
),
       
$string
   
);
}

// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);

/* Outputs:
string(34) "Quantity:\t500\nPrice:\t$5.25 each"
string(31) "Quantity:    500
Price:    $5.25 each"
*/

?>
dot dot dot dot dot alexander at gmail dot com
07-Feb-2008 07:31
I think there's not that much to string comparison as claiming date recognition:

It's simply comparing ordinal values of the characters from the {0} to the {strlen-1} one.
In this case
<?php
$a
= '2007-11-06 15:17:48';
$b = '2007-11-05 15:17:48';

var_dump($a > $b);
?>
mArIo@luigi ~ $: php test.php
bool(true)
here all characters match till it reaches position 9 (the "day")
there, 6 has a bigger ord()inal value than 5

<?php
$a
= 'January 25th, 2008 00:23:38';
$b = 'Janury 24th, 2008 00:23:37'; // ($a > $b) === false
?>
Here when we reach 'r' in "Janury" we see that "a" is "less" than "r" so the example would evaluate as ($a < $b) === true

Here:
<?php
$a
= 'February 1st, 2008 00:23:38';
$b = 'January 25th, 2008 00:23:38';
?>
as expected the letter "F" comes before "J" as an ordinal character, so $a is less than $b
 Even here:
<?php
var_dump
('Z' > 'M'); //bool(true)
?>
it gets confirmed that the string comparison operators >, <, =>, =<, == just do a ordinal character comparison starting from position {0} to the first difference or the end of the string.
topnotcher at mail dot uri dot edu
28-Jan-2008 05:25
@qriz at example dot com

Numerical comparisons, such as <, > are simply _NOT_ valid on strings.  Thus, before a comparison can be made by a numerical comparison operator, the operands must be _casted_ to a numerical type (either float or int).  What I was attempting to say in my previous post is that >, < are date-aware; the tests I included were examples, and not intended to represent the full scope of my comparison.

"Works correctly since there is a comparing between strings. The comparisson is done on the last number/letter (since thats the only thing that is difference in the string) and that is in this case: the 9 and 8."

What you say here is mere assumption; a few quick tests show that this is indeed not the case.  If PHP indeed compares only the last character in the string, then the following assertion should be false:

test.php:
<?php
$a
= '2007-11-06 15:17:48';
$b = '2007-11-05 15:17:48';

var_dump($a > $b);
?>
mArIo@luigi ~ $: php test.php
bool(true)

Further, consider the following choices for $a and $b, which, as expected, demonstrate that the <, > operators can indeed understand date formats:

<?php
$a
= 'January 25th, 2008 00:23:37';
$b = 'January 24th, 2008 00:23:38'; // ($a > $b) === true, but 8
?>

If you remain unconvinced, consider what happens if I spell January incorrectly:

<?php
$a
= 'January 25th, 2008 00:23:38';
$b = 'Janury 24th, 2008 00:23:37'; // ($a > $b) === false
?>

Looks like it can understand ISO 8601 date formats? (for more information, see http://en.wikipedia.org/wiki/ISO_8601)

Further investigation yields that this doesn't even work as it should:
<?php
$a
= 'February 1st, 2008 00:23:38';
$b = 'January 25th, 2008 00:23:38';

var_dump($a > $b); //bool(false)

var_dump(strtotime($a)); //int(1201843418)
var_dump(strtotime($b)); //int(1201238618)
var_dump(strtotime($a) - strtotime($b)); //int(604800)
?>
Keeping $b constant and varying the month in $a shows that this comparison correctly interprets the date with the following months: January,March,May,June,July,September,October,November.  Interestingly enough, these are all the months having the property that ord($a[0]) >= ord($b[0]).

<?php
var_dump
('Z' > 'M'); //bool(true)
?>

Conclusion:
The <,> comparison operators definitely have functionality that is undocumented, including date awareness; however, this functionality may not always work as expected and should not be trusted for portability.
yuchunjiang at gmail dot com
23-Jan-2008 03:38
this is the sql string that use the variable and and \' and function.It generate the correct result.
 
$sql1=<<<EOT
INSERT INTO hp_visitHistory ( col1,col2,col3)
VALUES ( NOW(), '{$col2}', '{$_SERVER['REQUEST_URI']}')
EOT;
echo $sql1;
qriz at example dot com
13-Nov-2007 06:54
<?php
$a
= '2007-11-05 15:17:49';
$b = '2007-11-05 15:17:48';

$bool = $a > $b;

var_dump($bool); //bool(true)
?>

works correctly since there is a comparing between strings. The comparisson is done on the last number/letter (since thats the only thing that is difference in the string) and that is in this case: the 9 and 8.

8 > 9 = true

if you want to compare the string as pure numbers then you must type cast it to numbers or type juggle it:

<?php
$a
= '2007-11-05 15:17:49';
$b = '2007-11-05 15:17:48';

$bool1 = ($a + 0) > ($b + 0);      // 2007 > 2007
$bool2 = (int) $a > (int) $b;        // 2007 > 2007
$bool3 = intval($a) > intval($b);  // 2007 > 2007

var_dump($bool1,$bool2,$bool3); //bool(false)
?>
topnotcher at mail dot uri dot edu
06-Nov-2007 01:48
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...
 */
rkfranklin+php at gmail dot com
26-Sep-2007 09:35
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++]}<br>";

// these print George
echo "{$myArray['Person'.$i]}<br>";
echo
"{$myArray["Person{$i}"]}<br>";

// These don't work
echo "{$myArray['Person$i']}<br>";
echo
"{$myArray['Person'$i]}<br>";

// These both throw fatal errors
// echo "$myArray[Person$i]<br>";
//echo "$myArray[Person{$i}]<br>";
?>
michael at mahemoff dot com
07-Jul-2007 09:51
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!
php at craigbuchek dot com
03-Jul-2007 11:32
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";
Richard Neill
01-Jun-2007 05:31
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"
og at gams dot at
26-Apr-2007 02:06
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
penda ekoka
24-Apr-2007 07:14
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;

?>
php at moechofe dot com
01-Apr-2007 05:44
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
bryant at zionprogramming dot com
27-Feb-2007 09:16
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';
}

?>
fmouse at fmp dot com
21-Feb-2007 07:20
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'
bishop
28-Mar-2006 10:58
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.
webmaster at rephunter dot net
30-Nov-2005 05:57
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;
DELETETHIS dot php at dfackrell dot mailshell dot com
01-Nov-2005 05:05
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.
lelon at lelon dot net
27-Oct-2004 09:01
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.
Jonathan Lozinski
06-Aug-2004 09:03
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.
www.feisar.de
28-Apr-2004 04:49
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
atnak at chejz dot com
12-Apr-2004 12:53
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.
dandrake
20-Jan-2004 12:41
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 <br>World";
?>

like in HTML.
philip at cornado dot com
12-Apr-2003 02:37
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.
03-Mar-2003 07: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.
vallo at cs dot helsinki dot fi
04-Nov-2002 02:41
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.
guidod at gmx dot de
23-Jul-2002 08:26
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!

配列> <浮動小数点数
Last updated: Fri, 10 Oct 2008