我想要得到一个字符串的第一个字母,我注意到$str[0]工作得很好。我只是不确定这是否是“良好的实践”,因为这种符号通常用于数组。这个特性似乎没有很好的文档记录,所以我想请你们来告诉我,从各个方面来说,使用这个符号是否正确?
或者我应该坚持使用好的ol' substr($str, 0,1)?
此外,我注意到花括号($str{0})也可以。这是怎么回事?
我想要得到一个字符串的第一个字母,我注意到$str[0]工作得很好。我只是不确定这是否是“良好的实践”,因为这种符号通常用于数组。这个特性似乎没有很好的文档记录,所以我想请你们来告诉我,从各个方面来说,使用这个符号是否正确?
或者我应该坚持使用好的ol' substr($str, 0,1)?
此外,我注意到花括号($str{0})也可以。这是怎么回事?
当前回答
我唯一怀疑的是,这种技术在多字节字符串上有多适用,但如果这不是一个考虑因素,那么我怀疑您已经被覆盖了。(如果有疑问,mb_substr()显然是一个安全的选择。)
然而,从大局的角度来看,我不得不考虑需要多久访问字符串中的第n个字符才能成为一个关键的考虑因素。
其他回答
$str = 'abcdef';
echo $str[0]; // a
在多字节(unicode)字符串的情况下,使用str[0]可能会导致麻烦。Mb_substr()是一个更好的解决方案。例如:
$first_char = mb_substr($title, 0, 1);
获取UTF-8字符串的第一个字符
我唯一怀疑的是,这种技术在多字节字符串上有多适用,但如果这不是一个考虑因素,那么我怀疑您已经被覆盖了。(如果有疑问,mb_substr()显然是一个安全的选择。)
然而,从大局的角度来看,我不得不考虑需要多久访问字符串中的第n个字符才能成为一个关键的考虑因素。
我以前也用过这个符号,没有副作用,也没有误解。这是有道理的——毕竟字符串只是一个字符数组。
它会根据资源而有所不同,但你可以运行下面的脚本,自己看看;)
<?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
似乎使用[]或{}操作符或多或少是一样的。