PHP:if语句中的boolean值

时间:2016-08-08 02:54:37

标签: php forms

if ($_POST) {
    $family = array("Rob", "Kirsten", "Tommy", "Ralphie");
    $isKnown = false;
    foreach ($family as $value) {
        if ($value == $_POST['name']) {
            $isKnown = true;
        }  
    }
    if ($isKnown) {
        echo "Hi there ".$_POST['name']."!";
    } else {
        echo "I don't know you.";
    }      
}

<form method="post">
    <p>What is your name?</p>
    <p><input type="text" name="name"></p>
    <p><input type="submit" value="Submit"></p>
</form>

现在isKnown = false但是在最后一个if语句中

if ($isKnown) {
     echo "Hi there ".$_POST['name']."!";
} else {
     echo "I don't know you.";
}

我无法理解......现在$isKnown = false并且当$isknown false isknown时说出true if时会说的代码1}} ...

我理解所有代码,但我唯一能做的就是$isKnown $isknown的价值是什么以及它是如何得到这个值的。

此if语句中true的价值是什么:falseFusionCharts.ready(function() { var demographicsChart = new FusionCharts({ type: 'pie2d', renderAt: 'chart-container', width: '450', height: '300', dataFormat: 'json', dataSource: { "chart": { "caption": "Age profile of website visitors", "subCaption": "Last Year", "startingAngle": "120", "showLabels": "0", "showLegend": "1", "enableMultiSlicing": "0", "slicingDistance": "15", "showPercentValues": "1", "showPercentInTooltip": "0", "plotTooltext": "Age group : $label<br>Total visit : $datavalue", "theme": "fint" }, "data": [{ "label": "Teenage", "value": "1250400" }, { "label": "Adult", "value": "1463300" }, { "label": "Mid-age", "value": "1050700" }, { "label": "Senior", "value": "491000" }] } }); demographicsChart.render(); });

2 个答案:

答案 0 :(得分:0)

代码按以下方式工作。如果您提交了表单,则只设置值$ isknown。如果设置,则$ isknown的默认值为false。

如果$ family中存在$ _POST ['name'],则$ isknown将设置为true。

现在有if($ isknown),如果$ isknown为真,它会回显你好$ _POST ['name']如果$ unknown是false,它会回显我不知道你

答案 1 :(得分:0)

因此,以下是您想要做的事情:

首先,我们通过表单发布$_POST['name']的值,然后将变量$isKnown的值设置为false

然后我们将在给定数组$_POST['name']中显示$family的值。

如果$_POST['name']$family数组中的某个值匹配,那么我们将$isKnown的值设置为true,最后我们将获取有关布尔值的消息$isKnown

实际上有一个较短的方法:

if(!empty($_POST['name'])){
 $family = array("Rob", "Kirsten", "Tommy", "Ralphie");


         if(in_array($_POST['name'], $family)){
            echo "Hi there ".$_POST['name']."!";
          }else{
            echo "I don't know you.";
          }
}