2

Possible Duplicate:
Get first element of an array

What is the fastest and easiest way to get the first item of an array in php? I only need the first item of the array saved in a string and the array must not be modified.

Community
  • 1
  • 1
LostPhysx
  • 3,573
  • 8
  • 43
  • 73

6 Answers6

4

I'd say that this is very optimized:

echo reset($arr);
ddinchev
  • 33,683
  • 28
  • 88
  • 133
2

I could not but try this out

$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;

Output

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

So the fastest is

 $item = &$array[0];
Baba
  • 94,024
  • 28
  • 166
  • 217
1

Use reset:

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

Note that the array's cursor is set to the beginning of the array when you use this.

Live demonstration

(Naturally, you can store the result into a string instead of echoing, but I use echo for demonstration purposes.)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Something like this?:

$firstitem = $array[0];
MatthewMcGovern
  • 3,466
  • 1
  • 19
  • 19
0

reset does this:

$item = reset($array);

This will work irrespective of what the keys are, but it will move the array pointer (I 've never had a reason to worry about this, but it should be mentioned).

Jon
  • 428,835
  • 81
  • 738
  • 806
0

The most efficient is getting the reference, so not string copy is involved:

$first = &$array[0];

Just make sure you don't modify $first, as it will be modified in the array too. If you have to modify it then look for the other answers alternatives.

Nelson
  • 49,283
  • 8
  • 68
  • 81