PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php花括号的用法是什么

藏色散人
藏色散人 原创
2021-09-10 09:59:01 2179浏览

php花括号的用法有多种,如:1、“function name(){}”或“for(){}”用法;2、“$str{4}”用法;3、“{$val}”用法。

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php花括号的用法是什么?

PHP的大括号(花括号{})使用详解

一、不管什么程序,function name(){}, for(){}, ….这太多了,不说也知道什么用了。

二、$str{4}在字符串的变量的后面跟上{}大括号和中括号[]一样都是把某个字符串变量当成数组处理。

三、{$val}这种情况就是我遇到的问题,这时候大括号起的作用就是,告诉PHP,括起来的要当成变量处理。

如下例子:

//The following is okay as it's inside a string. Constants are not
//looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]"; // Hello apple

//With one exception, braces surrounding arrays within strings
//allows constants to be looked for
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple

另:PHP 字符串变量中大括号(花括号{})的作用

PHP 变量后面加上一个大括号{},里面填上数字,就是指 PHP 变量相应序号的字符。

例如:

$str = 'hello';

echo $str{0}; // 输出为 h ,也可以 $str[0]
echo $str{1}; // 输出为 e ,也可以 $str[1]

如果要检查某个字符串是否满足多少长度,可以考虑用这种大括号(花括号)加 isset 的方式替代 strlen 函数,因为 isset 是语言结构,strlen 是函数,所以使用 isset 比使用 strlen 效率更高。

比如判断一个字符串的长度是否小于 5:

if  ( !isset ( $str{5} ) ) 就比 if  ( strlen ( $str )

推荐学习:《PHP视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。