PHP - iterate on string characters

前端 未结 9 902
失恋的感觉
失恋的感觉 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 14:30

    Hmm... There's no need to complicate things. The basics work great always.

        $string = 'abcdef';
        $len = strlen( $string );
        $x = 0;
    

    Forward Direction:

    while ( $len > $x ) echo $string[ $x++ ];
    

    Outputs: abcdef

    Reverse Direction:

    while ( $len ) echo $string[ --$len ];
    

    Outputs: fedcba

提交回复
热议问题