检查字符串长度是否大于或小于所需量的函数
我想创建一个函数来检查字符串的长度是否大于或小于所需的数量:
像这样的事情:
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;
}
}
问题是我不知道要返回什么。我不想返回“字符串太短”之类的内容。也许是一个数字,0
if == ""
,1
如果大于,2
如果小于?
这样做的正确方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以像许多比较函数一样返回
1
、0
和-1
。在这种情况下,返回值可能具有以下含义:0
:字符串长度在范围内-1
:太短1
:太长我认为没有适当的方法来做到这一点。您只需记录并解释返回值。
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 short1
: too longI don't think there is a proper way for this. You just have to document and explain the return values.
我会让函数返回一个布尔值,其中
TRUE
表示字符串在限制范围内,FALSE
表示字符串长度无效并更改代码部分使用该函数的地方。此外,我将重新设计该函数,如下所示:
使用该函数的代码部分可能如下所示:
I would have the function return a boolean value, where
TRUE
would mean that the string is within limits andFALSE
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:
The part of code where the function is used could look like this:
如果长度小于要求则返回 0 如果超过要求则返回 -1 如果在范围内则返回 1
if the length is lower than required then return 0 if more than required then -1 if within range then 1