Counting

Would You Prefer This

<?php

include ("mainfunctions.php") ;

$string = "Hello Jamie Today Is Saturday 16th April. " ;
$length = length ($string) ;

echo $length;

?>

This Bit Is mainfunctions.php

<?

function length ($text)
{
   return strlen ($text) ;
}
    
?>

Or Would You Prefer This

<?php

$string = "Hello Jamie Today Is Saturday 16th April. " ;
$length = strlen ($string) ;

echo $length;

?>

:lol:

For displaying the string length you could do:

<?php

$string = "Hello Jamie Today Is Saturday 16th April. " ;
echo strlen($string);

?>

I prefer the second option. It makes no sense to define an function that only executes another function. You don’t add anything to the language, and it only makes it confusing for other programmers if they ever have to work with your code.


function longness($text) {
  return charnum($text);
}

function charnum($text) {
  return stringsize($text);
}

function stringsize($text) {
  return length($text);
}

function length($text) {
  return strlen($string);
}

This is the most flexible way, because then you have the choice of calling strlen(), length(), stringsize(), charnum() or longness(). Choice is good :wink:


echo longness('Hello'); //5

^ too further expand on that awesome idea:


function longness($text) {
  return charnum($text);
}

function charnum($text) {
  return stringsize($text);
}

function stringsize($text) {
  return length($text);
}

function length($text) {
  return strlen($string);
} 

function howlong($text) {
  for ($=0;$x<1000000;$x++); // act as though we're pondering things over
  $x=rand(1,4);
  switch ($x) {
     case 1: return longness($text);
     case 2: return charnum($text);
     case 3: return stringsize($text);
     case 4: return length($text);
     default: return strlen($text);
  }
}

You all forgot the mb_strlen variations! :slight_smile: