PHP in_array() only matches value in the first array position
While trying to create a tagging function for a new blog system I’m currently building, I kept running into trouble when using is_array() to find the tags for each post.
Let’s say we have a tag array that was populated from a text file:
$tags = array( 'a', 'b', 'c' );
And now we want to check if a specific tag is in both arrays:
if ( in_array( 'a', $tags ) ) {
$response = 'Tag found';
} else {
$response = 'Tag not found';
}
As we expected, $response = ‘Tag found’. But if we search for ‘b’, $response = ‘Tag not found’ even though we can see very clearly that the value ‘b’ exists in the array $tags.
What’s the solution?
The key to the solution lies in the fact that the array $tags was populated from a text file. Text files can contain all sorts of hidden characters that in_array() can pick up when comparing parameters. The fix is simple. Before passing the $tags array to in_array(), trim up each of the array values like so:
$tags = array_map( 'trim', $tags );
This took me a good 3 hours to figure out. I hope you found this article in less time.
