[PHP字串]②--花括號{}的作用

weixin_33749242發表於2017-08-18
2953340-01205c6acb65e140.png
Paste_Image.png
$username = 'king';
//echo "my name is $kings";
echo "my name is {$username}s";//my name is kings
echo "<hr/>";
echo "my name is ${username}s";//my name is kings
2953340-64b0fa8445ba17a4.png
Paste_Image.png
2953340-e62a69aae74ba433.png
Paste_Image.png

查詢 修改

$str = 'abcdef';
echo $str{0};//a
echo "<hr/>";

$str{1} = 'm';
echo $str;//amcdef
echo "<hr/>";

//只能用一個字元修改一個字元
$str{4} = 'hello';
echo $str;//amcdhf
echo "<hr/>";

//中文在UTF8下佔三個字元
$str = "你好";
echo $str{0};
echo $str{1};
echo $str{2};//你
2953340-def971df9a47cced.png
Paste_Image.png

刪除

$str = "imooc";
$str{1} = '';
echo $str . "<br/>";  //iooc
var_dump($str);  //string 'i�ooc' (length=5)
2953340-61c54670f96e42d4.png
Paste_Image.png

新增

$str = 'abc';
$str{3} = 'def';
echo $str . "<br/>";//abcd
$str{5} = "fgh";
echo $str . "<br/>";//abcd f
var_dump($str);//string 'abcd f' (length=6)
2953340-023c83727989880c.png
Paste_Image.png

[]與{}效果相同

$str = 'hello';
echo $str[0] . "<br/>";//h

$string = 'sdsdsdsdkjfkgjfjkgfj';
echo $string{mt_rand(0, strlen($string) - 1)};//g
2953340-326a6d3975bd0a20.png
Paste_Image.png

思考:產生4位驗證碼

相關文章