tjhilder Posted August 9, 2009 Share Posted August 9, 2009 Hi, I've tried creating a small function that breaks up a string if longer than 15 characters but for some reason it's output is wrong. function str_break($string) { $str_limit = 15; if(strlen($string) >= $str_limit) { echo substr($string, 0, 15) . ".."; } else { echo $string; } } and then outputs this way: <?php echo $image_id . ": " . str_break($image) . "\n"; ?> but it outputs as if it is coded this way: <?php echo str_break($image) . $image_id . ": \n"; ?> what's wrong with it? Link to comment https://forums.phpfreaks.com/topic/169499-solved-breaking-up-a-string-based-on-a-limit-of-chars/ Share on other sites More sharing options...
.josh Posted August 9, 2009 Share Posted August 9, 2009 You are echoing the substr out in the function so that gets evaluated. Instead of echoing in the string inside the function, return it. Link to comment https://forums.phpfreaks.com/topic/169499-solved-breaking-up-a-string-based-on-a-limit-of-chars/#findComment-894303 Share on other sites More sharing options...
FD_F Posted August 9, 2009 Share Posted August 9, 2009 . Link to comment https://forums.phpfreaks.com/topic/169499-solved-breaking-up-a-string-based-on-a-limit-of-chars/#findComment-894307 Share on other sites More sharing options...
tjhilder Posted August 9, 2009 Author Share Posted August 9, 2009 ok I changed the code to: function str_break($string) { $str_limit = 15; if(strlen($string) >= $str_limit) { $string = substr($string, 0, 15) . ".."; } return $string; } and works now, cheers! Link to comment https://forums.phpfreaks.com/topic/169499-solved-breaking-up-a-string-based-on-a-limit-of-chars/#findComment-894308 Share on other sites More sharing options...
The Little Guy Posted August 9, 2009 Share Posted August 9, 2009 Don't use echo within functions, use return (which instantly breaks out of a function not executing any more code within the function): <?php function str_break($string){ $str_limit = 15; if(strlen($string) > $str_limit) return substr($string, 0, 15) . ".."; return $string; } echo $image_id . ": " . str_break($image) . "\n"; ?> Link to comment https://forums.phpfreaks.com/topic/169499-solved-breaking-up-a-string-based-on-a-limit-of-chars/#findComment-894312 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.