RE: [PHP-DEV] foreach() for strings

From: Date: Mon, 20 Jun 2011 14:18:43 +0000
Subject: RE: [PHP-DEV] foreach() for strings
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-53405@lists.php.net to get a copy of this message
On Mon Jun 20 09:11 AM, Lee davis wrote: > > Could we also use current(), next() and key() for iteration of strings? > > $string = 'string'; > while ($char = current($string)) > { > echo key($string) // Would output the offset position I assume 0,1,2 > etc?? > echo $char // outputs each letter of string > next($string); > } > Hopefully it can be supported without sacrificing too much performance Like others mentioned, it seems important to distinguish between binary/byte and text iteration. $string = new ByteIterator('string é'); foreach($string as $i => $byte) ... $string = new TextIterator('string é'); foreach($string as $i => $char) ... When most developers get a 'string' from a database, my hunch is they assume they would be iterating over the 'characters' (utf8, iso.. encoding) and not individual bytes. So +1 to string iteration as long as there's byte iteration and some plan for text iteration / by character (with icu or not).

« previous php.internals (#53405) next »