For those who are looking for a quick way to iterate over strings in php, Ive prepared test testing.
The first method in which you directly access string characters by specifying its position in brackets and treating the string as an array:
$string = "a sample string for testing"; $char = $string[4]
I myself thought that the latter is the fastest method, but I was mistaken.
As in the second method (which is used in the accepted answer):
$string = "a sample string for testing"; $string = str_split($string); $char = $string[4]
This method will be faster because we use a real array and do not assume that it is an array.
Calling the last line of each of the above methods for 1000000 times results in these benchmarking results:
Using string [i]
0.24960017204285 Seconds
Using str_split
0.18720006942749 Seconds
This means that the second method is faster.
AmirHossein Sep 02 '16 at 7:36 2016-09-02 07:36
source share