我想要得到一个字符串的第一个字母,我注意到$str[0]工作得很好。我只是不确定这是否是“良好的实践”,因为这种符号通常用于数组。这个特性似乎没有很好的文档记录,所以我想请你们来告诉我,从各个方面来说,使用这个符号是否正确?

或者我应该坚持使用好的ol' substr($str, 0,1)?

此外,我注意到花括号($str{0})也可以。这是怎么回事?


当前回答

$str = 'abcdef';
echo $str[0];                 // a

其他回答

我唯一怀疑的是,这种技术在多字节字符串上有多适用,但如果这不是一个考虑因素,那么我怀疑您已经被覆盖了。(如果有疑问,mb_substr()显然是一个安全的选择。)

然而,从大局的角度来看,我不得不考虑需要多久访问字符串中的第n个字符才能成为一个关键的考虑因素。

是的。字符串可以被视为字符数组,访问数组位置的方法是使用[]操作符。通常在使用$str[0]时没有任何问题(而且我非常确定它比substr()方法快得多)。

对于这两种方法只有一个警告:它们将获得第一个字节,而不是第一个字符。如果您正在使用多字节编码(如UTF-8),这很重要。如果您想要支持它,请使用mb_substr()。可以说,现在应该总是假设多字节输入,所以这是最好的选择,但它会稍微慢一些。

在多字节(unicode)字符串的情况下,使用str[0]可能会导致麻烦。Mb_substr()是一个更好的解决方案。例如:

$first_char = mb_substr($title, 0, 1);

获取UTF-8字符串的第一个字符

作为一个凡人,我会坚持使用$str[0]。就我而言,比起substr($str, 0,1),一眼就能更快地掌握$str[0]的含义。这可能归结为偏好问题。

就性能而言,概要文件概要文件概要文件。:)或者你可以查看一下PHP源代码…

它会根据资源而有所不同,但你可以运行下面的脚本,自己看看;)

<?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

似乎使用[]或{}操作符或多或少是一样的。