Re: foreach() for strings

From: Date: Mon, 20 Jun 2011 16:57:24 +0000
Subject: Re: foreach() for strings
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to internals+get-53431@lists.php.net to get a copy of this message
Adding to John Crenshaw's list of reasons not to implicitly treat strings as arrays in foreach loops... Please keep in mind the following valid code: $s = 'hello'; foreach ((array)$s as $x) { var_dump($x); } The result is: string(5) "hello" That behavior can be handy. Hopefully, a BC break wouldn't occur if any of the string features currently being discussed are implemented. Without a BC break, having strings implicitly be treated as arrays in foreach loops will seem very strange in cases like the above. Iterators are nice. Having a "text_string_to_array" function would also be fine. For example: $s = 'hello'; foreach (text_string_to_array($s) as $x) { var_dump($x); } The result would be: string(1) "h" string(1) "e" string(1) "l" string(1) "l" string(1) "o" I don't know enough about the internals to say for sure, but perhaps text_string_to_array() could be implemented as creating a reference to the string that has a flag set that causes it to be allowed to be treated as an array. (A full conversion might be needed it were written to. For example, $a = text_string_to_array($s); $a[0] = 5; ) - Todd

« previous php.internals (#53431) next »