note 44613 added to function.str-split
| From: | RickHull at osu1 dot php dot net | Date: | Wed, 11 Aug 2004 00:31:13 +0000 |
| Subject: | note 44613 added to function.str-split | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-79952@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.str-split.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44613
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44613&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44613&report=yes
Search -- http://master.php.net/manage/user-notes.php