php 检查变量长度是否等于一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1141629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:12:33  来源:igfitidea点击:

php check if variable length equals a value

php

提问by mrpatg

Need to check if $messagelength is 7 characters or less, if so, do action A, if not, do action B. Is this correct syntax? I think im doing something wrong?

需要检查$message长度是否为 7 个字符或更少,如果是,则执行操作 A,否则执行操作 B。这是正确的语法吗?我想我做错了什么?

<?php

if (strlen($message) <= 7) {
    echo $actiona;
} else {
    echo $actionb;
}

?>

回答by Evan Fosmark

It's fine. For example, let's run the following:

没关系。例如,让我们运行以下命令:

<?php

$message = "Hello there!";

if (strlen($message) <= 7){
    echo "It is less than or equal to 7 characters.";
} 
else 
{
    echo "It is greater than 7 characters.";
}
?>

It will print: "It is greater than 7 characters."

它将打印:“它大于 7 个字符。”

回答by Randell

You might also want to use the PHP shorthand if/else using the ternary operators (?:).

您可能还想使用 PHP 速记 if/else 使用三元运算符 (?:)。

For example, instead of:

例如,而不是:

<?php

if (strlen($message) <= 7) {
    echo $actiona;
} else {
    echo $actionb;
}

?>

You can write it as:

你可以把它写成:

<?php echo strlen($message) <= 7 ? $actiona : $actionb; ?>

See How do I use shorthand if / else?for information on the ternary operator.

请参阅如何使用速记 if / else?有关三元运算符的信息。

回答by EvilChookie

What error messages are you receiving?

您收到什么错误消息?

I would check that when you set $messagebefore hand, you haven't misspelt it or used incorrect capitalization (keeping in mind that php is cAsE sensitive).

我会检查当您$message事先设置时,您没有拼错或使用不正确的大写(请记住,php 是 cAsE 敏感的)。

回答by Pascal MARTIN

That's OK.

没关系。

But you should use long php tags (short tags can be disabled ; and quite often are) :

但是您应该使用长 php 标签(可以禁用短标签;而且通常是这样):

<?php
// ... PHP code
?>

(closing tag being optional, if your file contains only PHP)

(结束标记是可选的,如果您的文件只包含 PHP)

回答by Constantin

i found this ISSET "trick"around www , i don't remember where. try first to run the script like this then uncomment the 2nd line $message=.. to write over another string length..

我在 www 周围发现了这个ISSET“技巧”,我不记得在哪里。首先尝试像这样运行脚本,然后取消注释第二行 $message=.. 以覆盖另一个字符串长度..

<?php
$actiona="ACTIONA";
$actionb="ACTIONB";

$message="1234567";
//$message="12345678";//try to comment /uncomment these

if (!isset($message{7})) {
    echo $actiona;
} else {
    echo $actionb;
}
?>

AND SURE

当然

<?php
$actiona="ACTIONA";
$actionb="ACTIONB";

$message="1234567";//try to comment /uncomment these
//$message="12345678";


echo !isset($message{7}) ? $actiona : $actionb; 


?>

Good luck! We All Love Php !!!!

祝你好运!我们都爱 PHP !!!!