note 86824 modified in function.mb-split by felipe

From: Date: Wed, 05 Nov 2008 13:42:09 +0000
Subject: note 86824 modified in function.mb-split by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146157@lists.php.net to get a copy of this message
The code <?php function mbStringToArray ($string) { $strlen = mb_strlen($string); while ($strlen) { $array[] = mb_substr($string,0,1,"UTF-8"); $string = mb_substr($string,1,$strlen,"UTF-8"); $strlen = mb_strlen($string); } return $array; } ?> may be a bit inefficient cuz this asignment : <?php $string = mb_substr($string,1,$strlen,"UTF-8"); ?> in cycle is worth n-i operations, where n - is initial string length and i - the current cycle number. Total complexity of the algorithm becomes O(n*n / 2). I would like propose following algorithm: <?php mb_regex_encoding('UTF-8'); mb_internal_encoding('UTF-8' ); $strArray = array(); for ( $i=0; $i < mb_strlen($str); $i++ ) { $strArray[] = mb_substr($str, $i, 1) ; } ?> Now it depends on the complexity of the mb_substr($str, $i, 1). If it is constant, then the whole algorithm complexity becomes O(n) --was-- The code function mbStringToArray ($string) { $strlen = mb_strlen($string); while ($strlen) { $array[] = mb_substr($string,0,1,"UTF-8"); $string = mb_substr($string,1,$strlen,"UTF-8"); $strlen = mb_strlen($string); } return $array; } may be a bit inefficient cuz this asignment : $string = mb_substr($string,1,$strlen,"UTF-8"); in cycle is worth n-i operations, where n - is initial string length and i - the current cycle number. Total complexity of the algorithm becomes O(n*n / 2). I would like propose following algorithm: mb_regex_encoding('UTF-8'); mb_internal_encoding('UTF-8' ); $strArray = array(); for ( $i=0; $i < mb_strlen($str); $i++ ) { $strArray[] = mb_substr($str, $i, 1) ; } Now it depends on the complexity of the mb_substr($str, $i, 1). If it is constant, then the whole algorithm complexity becomes O(n) http://php.net/manual/en/function.mb-split.php

« previous php.notes (#146157) next »