The function of checking the length of the string is greater or less than the required amount

I want to create a function to check if the string length is longer or shorter than the required amount:

Something like that:

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 that I do not know what to return. I don't want to return something like "The string is too short." Maybe a number, 0 if == "" , 1 if more, 2 if less?

What would be the right way to do this?

+4
source share
4 answers

You can return 1 , 0 and -1 , as many comparison functions do. In this case, the return values ​​may have the following values:

  • 0 : string length is inside borders
  • -1 : too short
  • 1 : too long

I do not think there is a right way for this. You just need to document and explain the return values.

+6
source

I would like the function to return a boolean, where TRUE would mean that the string is within and FALSE means that the string length is invalid and will change the part of the code where the function is used.

In addition, I would revise the function as follows:

 function is_string_length_correct( $string, $min, $max ) { $l = mb_strlen($string); return ($l >= $min && $l <= $max); } 

The part of the code that uses this function may 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; } 
+4
source

if the length is less than what is required, then return 0, if it is required more than -1, if within the range, then 1

 function check_string_lenght($string, $min, $max) { if (strlen($string)<$min) return 0; elseif (strlen($string) > $max) return -1; else return 1; } 
0
source
 function checkWord_len($string, $nr_limit) { $text_words = explode(" ", $string); $text_count = count($text_words); for ($i=0; $i < $text_count; $i++){ //Get the array words from text // echo $text_words[$i] ; " //Get the array words from text $cc = (strlen($text_words[$i])) ;//Get the lenght char of each words from array if($cc > $nr_limit) //Check the limit { $d = "0" ; } } return $d ; //Return the value or null } $string_to_check = " heare is your text to check"; //Text to check $nr_string_limit = '5' ; //Value of limit len word $rez_fin = checkWord_len($string_to_check,$nr_string_limit) ; if($rez_fin =='0') { echo "false"; //Execute the false code } elseif($rez_fin == null) { echo "true"; //Execute the true code } 
0
source

Source: https://habr.com/ru/post/1346463/


All Articles