PHP - string character iteration

Is there a good way to iterate over the characters of a string? I would like to be able to do foreach , array_map , array_walk , array_filter etc. For string characters.

The casting / juggling type didn't get me anywhere (put the entire string as one element of an array), and the best solution I found is simply to use a for loop to build the array. There seems to be something better. I mean, if you can index it, shouldn't you iterate too?

This is the best I have

 function stringToArray($s) { $r = array(); for($i=0; $i<strlen($s); $i++) $r[$i] = $s[$i]; return $r; } $s1 = "textasstringwoohoo"; $arr = stringToArray($s1); //$arr now has character array $ascval = array_map('ord', $arr); //so i can do stuff like this $foreach ($arr as $curChar) {....} $evenAsciiOnly = array_filter( function($x) {return ord($x) % 2 === 0;}, $arr); 

Whether there is a:

A) A way to make a string iterable
B) The best way to build an array of characters from a string (and if so, what about a different direction?)

It seems to me that something is not so obvious with me.

+105
string php
Jan 05 2018-11-11T00:
source share
9 answers

Step 1: convert string to array with str_split function str_split

$array = str_split($your_string);

Step 2: loop through the newly created array

 foreach ($array as $char) { echo $char; } 

You can check the PHP documentation for more information: str_split

+150
Jan 05 2018-11-11T00:
source share

Line iteration:

 for ($i = 0; $i < strlen($str); $i++){ echo $str[$i]; } 
+66
Oct 24 '16 at 9:30
source share

If your lines are in Unicode, you should use preg_split with the /u modifier

From the comments in the php documentation:

 function mb_str_split( $string ) { # Split at all position not after the start: ^ # and not before the end: $ return preg_split('/(?<!^)(?!$)/u', $string ); } 
+19
Jan 08 '12 at 18:28
source share

You can also just access $ s1 as an array if you only need to access it:

 $s1 = "hello world"; echo $s1[0]; // -> h 
+9
Feb 18 '16 at 21:47
source share

Deployed from @SeaBrightSystems answer, you can try the following:

 $s1 = "textasstringwoohoo"; $arr = str_split($s1); //$arr now has character array 
+6
May 15 '15 at 7:55
source share

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] // equals to m 

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] // equals to m 

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.

+5
Sep 02 '16 at 7:36
source share

Hmm ... No need to complicate things. The basics work great always.

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

Direct direction:

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

Outputs: abcdef

Reverse direction:

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

Outputs: fedcba

+3
Dec 21 '18 at 6:19 06:19
source share
 // Unicode Codepoint Escape Syntax in PHP 7.0 $str = "cat!\u{1F431}"; // IIFE (Immediately Invoked Function Expression) in PHP 7.0 $gen = (function(string $str) { for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) { yield mb_substr($str, $i, 1); } })($str); var_dump( true === $gen instanceof Traversable, // PHP 7.1 true === is_iterable($gen) ); foreach ($gen as $char) { echo $char, PHP_EOL; } 
+2
Aug 29 '16 at 5:04 on
source share

Most answers have forgotten about non-English characters !!!

strlen counts BYTEs, not characters, so it and its related functions work fine with English characters, since English characters are stored in 1 byte in UTF-8 and ASCII encodings, you need to use multibyte code string functions mb_*

This will work with any character encoded in UTF-8

 // 8 characters in 12 bytes $string = "abcdأبتث"; $charsCount = mb_strlen($string, 'UTF-8'); for($i = 0; $i < $charsCount; $i++){ $char = mb_substr($string, $i, 1, 'UTF-8'); var_dump($char); } 

It outputs

 string(1) "a" string(1) "b" string(1) "c" string(1) "d" string(2) "أ" string(2) "ب" string(2) "ت" string(2) "ث" 
0
Sep 01 '19 at 17:15
source share



All Articles