1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I took this one. Easier. But wonder why there is no simple search like I wanted, in PHP. Thanks anyways!
1

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

2 Comments

What does the last one return? How do we know all $flds exists or not in $ret? We need to do another condition for count?
The last one is a boolean comparison. First it creates an array that contains all elements in $flds that are not keys of $ret. Then it checks if this array is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.