Its easy to test which one is faster thought..
<?php
$string = "My name is stephen and i dont know how to do stuff or things.";
$time_s = microtime_float();
for ($i2=0; $i2<1000; $i2++) {
$output = getwords($string,5);
}
$time_e = microtime_float();
echo $time_e - $time_s."\n";
$time_s = microtime_float();
for ($i2=0; $i2<1000; $i2++) {
$output = '';
for( $i=0,$w=0;$i<strlen($string);$i++ ) {
if( $string{$i} == ' ' AND ++$w==5 ) break;
$output .= $string{$i};
}
}
$time_e = microtime_float();
echo $time_e - $time_s."\n";
function getwords($string,$numwords) {
$tmp = explode(' ',$string);
array_splice($tmp, $numwords);
return(implode(' ',$tmp));
}
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>
Actually my way is much faster 🙂 Heres the output from shell. Upper time is from my function and other is halfabee's
cahva@karhu:~$ php timetest.php
0.28144288063049
1.1363370418549
cahva@karhu:~$ php timetest.php
0.28236603736877
1.1340301036835
cahva@karhu:~$ php timetest.php
0.28396701812744
1.1284329891205
cahva@karhu:~$ php timetest.php
0.28598999977112
1.2064080238342
Machine is 300Mhz P3 so its a little slow 😃