[英]php in array returning false when value does exist
Simple one here, but hurting ones head. 这里很简单,但是伤到了头脑。
echo in_array('275', $searchMe);
is returning false. 是假的。 But if I print the array out and then search it manually using my web browser I am able to see that the value exists in the array. 但是,如果我打印出阵列,然后使用我的Web浏览器手动搜索它,我可以看到数组中存在该值。
[0] => ExtrasInfoType Object
(
[Criteria] =>
[Code] => 275
[Type] => 15
[Name] => Pen
)
Extra information. 额外的信息。 The array has been coverted from an object to an array using 数组已使用从一个对象转换为一个数组
$searchMe = (array) $object;
Would it be because the values are not quoted? 是不是因为没有引用这些值? I have tried using the following with the in_array
function: 我已尝试将以下内容与in_array
函数一起使用:
echo in_array('275', $searchMe); // returns false
echo in_array(275, $searchMe); // returns error (Notice: Object of class Extras could not be converted to int in)
var_dump of $searchMe $ searchMe的var_dump
array
'Extras' =>
object(Extras)[6]
public 'Extra' =>
array
0 =>
object(ExtrasInfoType)[7]
...
1 =>
object(ExtrasInfoType)[17]
...
2 =>
object(ExtrasInfoType)[27]
...
One scenario I think that would be helpful. 我认为有一种情况会有所帮助。
If the array index that contains the value is 0, the returning value of in_array would be 0. If in our logic, 0 is considered as false, then there will be issues. 如果包含该值的数组索引为0,则in_array的返回值将为0.如果在我们的逻辑中,0被视为false,则会出现问题。 Avoid this pattern in your code. 在代码中避免使用此模式。
in_array
can't see inside the ExtrasInfoType Object
. in_array
无法在ExtrasInfoType Object
看到。 Basically its comparing ExtrasInfoType Object
to 275
, which in this case returns false
. 基本上它将ExtrasInfoType Object
与275
进行比较,在这种情况下返回false
。
You have an object there, use... 你有一个对象,使用...
// Setup similar object
$searchMe = new stdClass;
$searchMe->Criteria = '';
$searchMe->Code = 275;
$searchMe->Type = 15;
$searchMe->Name = 'Pen';
var_dump(in_array('275', (array) $searchMe)); // bool(true)
When I cast ( (array)
) to an array, I got... 当我将( (array)
)转换为数组时,我得到了......
array(4) {
["Criteria"]=>
string(0) ""
["Code"]=>
int(275)
["Type"]=>
int(15)
["Name"]=>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.