Kevin Rave
Kevin Rave

Reputation: 14426

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.

  $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.

Anything wrong here?

Upvotes: 1

Views: 2734

Answers (2)

ksiimson
ksiimson

Reputation: 603

in_array() function searches whether the element is an element of the 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

Upvotes: 1

Scott Saunders
Scott Saunders

Reputation: 30394

That code is looking for the entire $flds array to be a value in $ret;

You'll probably want to use array_intersect() and then check the length of the result.

Upvotes: 4

Related Questions