我想要得到一个字符串的第一个字母,我注意到$str[0]工作得很好。我只是不确定这是否是“良好的实践”,因为这种符号通常用于数组。这个特性似乎没有很好的文档记录,所以我想请你们来告诉我,从各个方面来说,使用这个符号是否正确?
或者我应该坚持使用好的ol' substr($str, 0,1)?
此外,我注意到花括号($str{0})也可以。这是怎么回事?
我想要得到一个字符串的第一个字母,我注意到$str[0]工作得很好。我只是不确定这是否是“良好的实践”,因为这种符号通常用于数组。这个特性似乎没有很好的文档记录,所以我想请你们来告诉我,从各个方面来说,使用这个符号是否正确?
或者我应该坚持使用好的ol' substr($str, 0,1)?
此外,我注意到花括号($str{0})也可以。这是怎么回事?
当前回答
假设你只是想要$_POST的一部分的第一个字符,让我们称之为“类型”。并且$_POST['type']目前是'Control'。如果在这种情况下,如果你使用$_POST['type'][0],或substr($_POST['type'], 0,1),你将得到C。
然而,如果客户端要修改他们发送给你的数据,例如从类型到类型[],然后发送'Control'和'Test'作为该数组的数据,$_POST['type'][0]现在将返回Control而不是C,而substr($_POST['type'], 0,1)将简单地失败。
是的,使用$str[0]可能会有问题,但这取决于周围的环境。
其他回答
$str = 'abcdef';
echo $str[0]; // a
它会根据资源而有所不同,但你可以运行下面的脚本,自己看看;)
<?php
$tests = 100000;
for ($i = 0; $i < $tests; $i++)
{
$string = md5(rand());
$position = rand(0, 31);
$start1 = microtime(true);
$char1 = $string[$position];
$end1 = microtime(true);
$time1[$i] = $end1 - $start1;
$start2 = microtime(true);
$char2 = substr($string, $position, 1);
$end2 = microtime(true);
$time2[$i] = $end2 - $start2;
$start3 = microtime(true);
$char3 = $string{$position};
$end3 = microtime(true);
$time3[$i] = $end3 - $start3;
}
$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;
$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;
$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>
一些参考号(在旧的CoreDuo机器上)
$ php 1.php
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6
$ php 1.php
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6
$ php 1.php
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6
似乎使用[]或{}操作符或多或少是一样的。
假设你只是想要$_POST的一部分的第一个字符,让我们称之为“类型”。并且$_POST['type']目前是'Control'。如果在这种情况下,如果你使用$_POST['type'][0],或substr($_POST['type'], 0,1),你将得到C。
然而,如果客户端要修改他们发送给你的数据,例如从类型到类型[],然后发送'Control'和'Test'作为该数组的数据,$_POST['type'][0]现在将返回Control而不是C,而substr($_POST['type'], 0,1)将简单地失败。
是的,使用$str[0]可能会有问题,但这取决于周围的环境。
{}语法从PHP 5.3.0起已弃用。建议使用方括号。
作为一个凡人,我会坚持使用$str[0]。就我而言,比起substr($str, 0,1),一眼就能更快地掌握$str[0]的含义。这可能归结为偏好问题。
就性能而言,概要文件概要文件概要文件。:)或者你可以查看一下PHP源代码…