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
Paedow
  • 3,501
  • 8
  • 40
  • 71

6 Answers6

5

I'd say that this is very optimized:

echo reset($arr);
ddinchev
  • 31,743
  • 28
  • 84
  • 127
3

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
  • 92,047
  • 28
  • 163
  • 215
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
  • 369,052
  • 73
  • 620
  • 1,021
0

Something like this?:

$firstitem = $array[0];
MatthewMcGovern
  • 3,388
  • 1
  • 18
  • 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
  • 413,451
  • 75
  • 717
  • 787
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
  • 46,753
  • 8
  • 64
  • 79