PHP 教學 - 有趣的變數字串串接

假設我們需要變數和變數串接或者是變數字串串接該怎麼做呢?
從PHP官網中可得知我們可以利用.符號來串接,但其實還有另一種串接變數符號就是利用{}
範例如下
<?php
$str1 = "1";
$str2 = "2";
$str3 = "3";
echo "{$str1}[1]{$str2}[2]{$str3}</br>"; // one concat = fast
echo $str1. $str2. $str3;   // two concats = slow
?>
從另一個例子就更清楚表現字串與變數的串接
<?php
$a = '12345</br>';
// This works:
echo "qwe{$a}rty</br>"; // qwe12345rty, using braces
echo "qwe" . $a . "rty</br>"; // qwe12345rty, concatenation used
// Does not work:
echo 'qwe{$a}rty</br>'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
?>


留言

這個網誌中的熱門文章

c語言-關於#define用法

PHP教學 - 資料型態(Data Type) - 上

CMD常用網管指令