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.

Oh great. I’ve gone full-nerd

Oh great. I’ve gone full-nerd.

You never go full-nerd…

New WordPress Plugin – WP Slider.js

I just wanted to let you know about a plugin I’m currently working on. Yeah. It’s yet another feature/image slider but this one is based on the new, beautiful Slider.js by Gaetan Renaudeau.

WP Slider.js will allow you to pull the featured images from any category and create a slider with one simple template tag. Read more about the plugin on the project page. I hope that you will enjoy this plugin as much as I have.

The excitement and wonder of the dog park

  1. Buy a pair of GoPro HD cameras
  2. Strap to dog
  3. ???????
  4. Profit!

New, beautiful icons from WebDesign Tuts+

WebDesign Tuts+ has released a set of 50 icons to use in your own web designs. Get the files here.

Bad Behavior has blocked 166 access attempts in the last 7 days.