UPDATE:
A more complete benchmark script:
$start = $first = $str = null;//create vars, don't benchmark this
//time preg_match
$start = microtime(true);
$first = $str = implode(',', range(213,9999));
if (preg_match('/^[^,]+/', $str, $match))
{
$first = $match[0];
}
echo $first, PHP_EOL, microtime(true) - $start, ' time taken<br/>', PHP_EOL;
//time str* functions
$start = microtime(true);
$first = $str = implode(',', range(213,9999));
$first = substr($str, 0, strpos($str, ','));
echo $first, PHP_EOL, microtime(true) - $start, ' time taken<br/>', PHP_EOL;
//now explode + current
$first = null;
$start = microtime(true);
$str = implode(',', range(213, 9999));
$first = current(explode(',', $str));
echo $first, PHP_EOL, microtime(true) - $start, ' time taken';
The result varried a little, but after 100 runs, the averages amounted to:
#1 substr+strpos: ~.0022ms as 1//base for speed
#2 preg_match: ~.0041 as ~2//about twice as slow as #1
#3 explode: ~.00789 as ~4//about 4 times <=> #1, twice as slow <=> regex
You're absolutely right, exploding a string, constructing an array to get just the first value is a waste of resources, and it is not the fastest way to get what you want.
Some might run to regex for help, and chances are that, in your case that will be faster. But nothing I can think of will beat the speed of PHP's string functions (which are very close to the C string functions). I'd do this:
$first = substr($var, 0, strpos($var, ','));
If the comma isn't present (say $var = '123'
), then your current approach will assign 123
to $first
. To preserve this behaviour, I'd go for:
$first = strpos($var, ',') === false ? $var : substr($var, 0, strpos($var, ','));
This is to say: if strpos
returns false, then there is no comma at all, so assign the entire string to $first
, else get everything in front of the first comma.
For completeness sake (and after some initial bench-marking), using preg_match
did indeed prove to be faster than using explode
with large strings ($var = implode(',', range(1, 9999));
), when using this code:
$first = $var = implode(',', range(1,9999));
if (preg_match('/^[^,]*/',$var, $match))
{
$first = $match[0];
}
But honestly, I wouldn't use regex in this case.
In the interest of fairness, and to to clarify how I found the regex to be faster:
$start = microtime(true);
$first = $str = implode(',', range(213,9999));
if (preg_match('/^[^,]+/', $str, $match))
{
$first = $match[0];
}
echo $first, PHP_EOL, $str, PHP_EOL, microtime(true) - $start, ' time taken';
$first = null;
$start = microtime(true);
$str = implode(',', range(213, 9999));
$first = current(explode(',', $str));
echo $first, PHP_EOL, microtime(true) - $start, ' time taken';