简体   繁体   English

PHP中的in_array函数始终返回false

[英]in_array function in php always returns false

I have an array like this. 我有这样的数组。

  $flds = array("fn", "ln", "em");

I have another associative array like this. 我有另一个这样的关联数组。 this is dynamically returned from JSON POST. 这是从JSON POST动态返回的。

  $ret = array("fn" => "xyz", "ln" => "abc", "em" => "s.2", "another" => "123")

I want to search if the first array is existing in the 2nd array. 我想搜索第二个数组中是否存在第一个数组。 I did this: 我这样做:

  if ( in_array( $flds, array_keys($ret))) 
      echo "exists";
  else 
      echo "does not";

It always returns "does not". 它总是返回“不”。 When I print, $flds and array_keys($ret), both look exactly same. 当我打印$ flds和array_keys($ ret)时,它们看起来完全一样。

Anything wrong here? 这里有什么问题吗?

That code is looking for the entire $flds array to be a value in $ret; 该代码正在寻找整个$ flds数组作为$ ret中的值;

You'll probably want to use array_intersect() and then check the length of the result. 您可能需要使用array_intersect() ,然后检查结果的长度。

in_array() function searches whether the element is an element of the array. in_array()函数搜索该元素是否为数组的元素。 In your case, you want to determine whether the first array is a subset of keys in the second array. 在您的情况下,您想确定第一个数组是否是第二个数组中键的子集。 Let me show you what works and what does not work: 让我向您展示哪些有效,哪些无效:

/* check if 'fn' is an array key key of $ret */
in_array('fn', array_keys($ret)) // true

/* check if array('fn') is an element of array(array('fn'), 'en') */
in_array(array('fn'), array(array('fn'), 'en')) // true

/* check if $flds is a key of $ret */
in_array( $flds, array_keys($ret)) // false

/* check if all elements of $flds are also keys of $ret */
array() === array_diff($flds, array_keys($ret)) // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM