PHP - iterate on string characters

前端 未结 9 877
失恋的感觉
失恋的感觉 2020-12-04 14:01

Is there a nice way to iterate on the characters of a string? I\'d like to be able to do foreach, array_map, array_walk, array_

9条回答
  •  萌比男神i
    2020-12-04 14:33

    For those who are looking for the fastest way to iterate over strings in php, Ive prepared a benchmark testing.
    The first method in which you access string characters directly by specifying its position in brackets and treating string like an array:

    $string = "a sample string for testing";
    $char = $string[4] // equals to m
    

    I myself thought the latter is the fastest method, but I was wrong.
    As with the second method (which is used in the accepted answer):

    $string = "a sample string for testing";
    $string = str_split($string);
    $char = $string[4] // equals to m
    

    This method is going to be faster cause we are using a real array and not assuming one to be an array.

    Calling the last line of each of the above methods for 1000000 times lead to these benchmarking results:

    Using string[i]
    0.24960017204285 Seconds

    Using str_split
    0.18720006942749 Seconds

    Which means the second method is way faster.

提交回复
热议问题