Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to check if string length in greater than or less than required amount

Tags:

php

strlen

I want to create a function to check if the length of a string is greater than or less than a required amount:

Something like this:

function check_string_lenght($string, $min, $max)
{
 if ($string == "")
 {
   return x;   
 }
 elseif (strlen($string) > $max)
 {
   return y;
 } 
 elseif (strlen($string) < $min)
 {
   return z;
 }
 else
 {
   return $string;
 }

}

The problem is I don't know what to return. I don't want to return something like 'String is too short'. Maybe a number, 0 if == "", 1 if greater than, 2 if less than?

What would be the proper way of doing this?

like image 356
johnathan ross Avatar asked Dec 21 '22 15:12

johnathan ross


2 Answers

You can return 1, 0 and -1 like a lot of comparison functions do. In this case the return values could have these meanings:

  • 0: The string length is inside the bounds
  • -1: too short
  • 1: too long

I don't think there is a proper way for this. You just have to document and explain the return values.

like image 150
Felix Kling Avatar answered May 16 '23 06:05

Felix Kling


I would have the function return a boolean value, where TRUE would mean that the string is within limits and FALSE would mean that the string length is invalid and change the part of code where the function is used.

Furthermore, I would redesign the function as following:

function is_string_length_correct( $string, $min, $max ) {

    $l = mb_strlen($string);
    return ($l >= $min && $l <= $max);
}

The part of code where the function is used could look like this:

if (!is_string_length_correct($string, $min, $max)) {
    echo "Your string must be at least $min characters long at at 
        most $max characters long";
    return;
}
like image 22
Anax Avatar answered May 16 '23 07:05

Anax