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.
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.
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];
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.
(Naturally, you can store the result into a string instead of echo
ing, but I use echo
for demonstration purposes.)
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.