【问题标题】:What is the fastest way to get the first item of an array? [duplicate]获取数组第一项的最快方法是什么? [复制]
【发布时间】:2012-09-28 14:25:57
【问题描述】:

可能重复:
Get first element of an array

在php中获取数组第一项的最快和最简单的方法是什么? 我只需要将数组的第一项保存在字符串中,并且不能修改数组。

【问题讨论】:

  • 保存在字符串中的数组?你能举个这个数组的例子吗?
  • @Ikke:我认为他的意思是他希望将数组的第一项保存在字符串中。数组不能保存在字符串中。

标签: php arrays performance


【解决方案1】:

像这样?:

$firstitem = $array[0];

【讨论】:

  • 仅适用于数字键。
  • 仅适用于按数字顺序排列的数字键。
  • 没错,但他确实要求最快:P
  • 也许是最快的失败方式
【解决方案2】:

使用reset:

<?php
$array = Array(0 => "hello", "w" => "orld");
echo reset($array);
// Output: "hello"
?>

注意,当你使用这个时,数组的光标会设置在数组的开头。

Live demonstration

(当然,您可以将结果存储为字符串而不是echoing,但我使用echo 进行演示。)

【讨论】:

  • 我不知道有这样的功能。
  • @Veseliq: uk.php.net/reset -- 现在你是!
  • 您在编辑前建议begin() :)
  • @Veseliq:什么编辑?!你产生幻觉了……! ;)
【解决方案3】:

我会说这是非常优化的:

echo reset($arr);

【讨论】:

    【解决方案4】:

    reset 这样做:

    $item = reset($array);
    

    无论键是什么,这都会起作用,但它会移动数组指针(我从来没有有理由担心这一点,但应该提及)。

    【讨论】:

      【解决方案5】:

      最有效的是获取引用,所以不涉及字符串复制:

      $first = &$array[0];
      

      请确保您不要修改$first,因为它也会在数组中被修改。如果您必须修改它,请寻找其他答案替代方案。

      【讨论】:

      • 但这不会将任何内容存储到字符串中。
      • @LightnessRacesinOrbit 它只存储引用,而不是内容,这就是它最有效的原因。
      • 这也是它不回答问题的原因。
      【解决方案6】:

      我只能试试这个

      $max = 2000;
      $array = range(1, 2000);
      echo "<pre>";
      
      $start = microtime(true);
      for($i = 0; $i < $max; $i ++) {
           $item = current($array);
      }
      echo  microtime(true) - $start  ,PHP_EOL;
      
      
      $start = microtime(true);
      for($i = 0; $i < $max; $i ++) {
           $item = reset($array);
      }
      echo  microtime(true) - $start  ,PHP_EOL;
      
      
      $start = microtime(true);
      for($i = 0; $i < $max; $i ++) {
          $item = $array[0];
      }
      echo  microtime(true) - $start  ,PHP_EOL;
      
      
      
      $start = microtime(true);
      for($i = 0; $i < $max; $i ++) {
          $item = &$array[0];
      }
      echo  microtime(true) - $start  ,PHP_EOL;
      
      
      $start = microtime(true);
      for($i = 0; $i < $max; $i ++) {
           $item = array_shift($array);
      }
      echo  microtime(true) - $start  ,PHP_EOL;
      

      输出

      0.03761100769043
      0.037437915802002
      0.00060200691223145  <--- 2nd Position
      0.00056600570678711  <--- 1st Position
      0.068138122558594
      

      所以最快的是

       $item = &$array[0];
      

      【讨论】:

      • 但他想要的是字符串,而不是引用。
      • @Lightness Races in Orbit 参考仅供参考
      • 虽然第一个元素并不总是在 [0] 之下
      猜你喜欢
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2011-03-30
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多