开发者

PHP Most Efficient way to Convert a String with Commas Separating Values to an Array?

开发者 https://www.devze.com 2023-03-08 22:20 出处:网络
I\'ve done some searching around and most posts are using the php explode function to separate a string and store its values into an array.

I've done some searching around and most posts are using the php explode function to separate a string and store its values into an array.

I need an开发者_JS百科 efficient way to convert:

$string = "45,34,65,57,45,23,26,72,73,56";

To an array, so I can access single values using $array[3].

Is there a better method than explode?


Explode is the fastest method of splitting a string into an array, since it is a naive string reader searching for a delimiter. There is no regex engine overhead involved in this like with split/preg_split/ereg, etc. The only way you could improve performance would be splitting hairs on a mouse's back, and that would be to single quote your string array so that it's not parsed for variables.

However, given the size of your example array, you could calculate pi to the number of decimal places equivalent to the value of each number in the array and still not even scratch the surface of a performance problem.


$desiredPart = 3;

$num = strtok($string, ',');
$part = 1;

while ($part < $desiredPart && $num !== false) {
    $num = strtok(',');
    $part++;
}

echo $num;

This is probably the most efficient if you need to handle really long, and I mean really long, strings. For anything of the size you have posted as example, use explode.


If your parts are all the same length, just do:

$desiredPart = 3;
$partLength = 2;
$num = substr($string, ($partLength + 1) * ($desiredPart - 1), $partLength);


If the length of the parts is constant, you can check performance of the str_split method.

http://www.php.net/manual/en/function.str-split.php


You could use regular expression but that would be slower than explode()


The explode() method is quickest.

preg_split() is a more flexible alternative, but it's much slower.


whats wrong with explode?

you could use regex / substring, but those are slow in both development / runtime.
best of all, explode is done for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消