PHP的in_array功能古怪的行为 [英] Odd behaviour with PHP's in_array function
问题描述
我有多个检查表单条目,再返回布尔值(true),如果检查通过或这是如果它没有通过运行检查名称的功能。我建成运行一次多张支票的功能,所以它会返回这些结果的数组(一个结果每个已运行检查)。当我运行的功能,我得到这个数组结果:
I have a function that checks multiple form items and returns either boolean(true) if the check passed or the name of the check that was run if it didn't pass. I built the function to run multiple checks at once, so it will return an array of these results (one result for each check that was run). When I run the function, I get this array result:
Array ( [0] => 1 [1] => password [2] => birthday ) // print_r
array(3) { [0]=> bool(true) [1]=> string(8) "password" [2]=> string(8) "birthday" } // var_dump
用户名查看过去了,密码和生日同时检查失败。然后我使用简单的 in_array
语句来确定哪些失败了,就像这样:
The 'username' check passed and the 'password' and 'birthday' checks both failed. Then I am using simple in_array
statements to determine which ones failed, like so:
$results = $ani->e->vld->simulate("register.php", $checks);
die(var_dump($results)); // Added after to see what array was being returned
if (in_array("username", $results)) // do something
if (in_array("password", $results)) // do something
if (in_array("birthday", $results)) // do something
我遇到的问题是,在用户名行仍在执行,即使是那些用户名是不是数组中为止。它执行所有三个语句,好像他们是所有真正出于某种原因。为什么是这样?我想也许是,布尔(真)已自动导致功能不检查数组的休息每个结果返回true,但我无法找到会建议很奇怪功能的任何文档。
The problem I'm having is that the 'username' line is still executing, even those 'username' is not in the array. It executes all three statements as if they were all true for some reason. Why is this? I thought maybe that the bool(true) was automatically causing the function to return true for every result without checking the rest of the array, but I couldn't find any documentation that would suggest that very odd functionality.
推荐答案
您是对的。 用户名==真
计算结果为真正
,引起 in_array()
返回真正
。使用严
标记。这将导致函数使用用户名===真正
,其计算结果为假
。在PHP中,一个字符串真正
,除非它是空的。和 ===
运营商检查键入除了数值。
You are right. "username" == true
evaluates to true
, causing in_array()
to return true
. Use the strict
flag. That will cause the function to use "username" === true
, which evaluates to false
. In PHP, a string is true
unless it is empty. And the ===
operator checks type in addition to value.
这篇关于PHP的in_array功能古怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!