note 44613 deleted from function.str-split by aidan

From: Date: Thu, 26 Aug 2004 23:15:58 +0000
Subject: note 44613 deleted from function.str-split by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-75386@lists.php.net to get a copy of this message
Note Submitter: Rick Hull ---- Here's how I would do it: I renamed a few variables. $tmp_str became $str_ary. In my code, I would think that $tmp_str was a string, rather than an array. $offset became $cursor. A cursor is a better metaphor for an iterator. An offset implies a reference location plus or minus some distance -- does not apply here. Also, precalculate strlen($str) so that you don't call the function every time the for loop interates. Also, when $len == 1, we can avoid the use of substr(). <?php function str_split($str, $len=1) { if ($len < 1) return false; $str_ary = array(); $input_len = strlen($str); // don't use substr unless you have to if($len == 1) for($cursor = 0; $cursor < $input_len; $cursor++) $str_ary[] = $str{$cursor}; else for ($cursor = 0; $cursor < $input_len; $cursor += $len) $str_ary[] = substr($str, $offset, $len); return $str_ary; } ?>

« previous php.notes (#75386) next »