<?php
function wordsToArr2($str) {
$words = [$str];
while ($pos =strpos ( $str , ' ')) {
$str=substr($str,($pos+1));
$words[] =$str;
}
return $words;
}
function wordsToArr3($str) {
$base = array_reverse(explode(' ', $str));
$words = [$placeholder = array_shift($base)];
foreach ($base as $word) {
$words[] = $placeholder = $word . ' ' . $placeholder;
}
return array_reverse($words);
}
function wordsToArr4($str) {
$base = explode(' ', $str);
end($base);
$l = key($base);
$words = [$placeholder = $base[$l--]];
for ($i=$l; $i>=0;$i--) {
$words[] = $placeholder = $base[$i] . ' ' . $placeholder;
}
return array_reverse($words);
}
function wordsToArr5($str) {
$base = str_word_count($str, 1);
$l = count($base)-1;
$words = [$placeholder = $base[$l--]];
for ($i=$l; $i>=0;$i--) {
$words[] = $placeholder = $base[$i] . ' ' . $placeholder;
}
return array_reverse($words);
}
function wordsToArr2($str) {
$words = [];
$ph = '';
while ($ph !== $str) {
$words[] = $ph = substr($ph, strpos( $str , ' ', -1));
}
return $words;
}
function bench($callback, $arg, $runs = 100) {
$t = 0;
$now = microtime(true);
for ($i=0; $i<$runs; $i++) {
$callback($arg);
}
$t += (microtime(true) - $now);
return [number_format($t, 8), $i];
}
$sentence = 'The quick brown fox jumps over the lazy dog';
$ph = $sentence;
$ph = substr($ph, strpos($ph , ' ', -1));
var_dump($ph);
exit;
list($t, $i) = bench('wordsToArr2', $sentence);
echo 'strpos '. $i .' times in: ' . $t . '/sec' . PHP_EOL;
list($t, $i) = bench('wordsToArr3', $sentence);
echo 'concat '. $i .' times in: ' . $t . '/sec' . PHP_EOL;
list($t, $i) = bench('wordsToArr4', $sentence);
echo 'end/key '. $i .' times in: ' . $t . '/sec' . PHP_EOL;
list($t, $i) = bench('wordsToArr5', $sentence);
echo 'count-- '. $i .' times in: ' . $t . '/sec' . PHP_EOL;
preferences:
154.46 ms | 1397 KiB | 8 Q