WarpConduit Computing

  • Quick Tips
  • Web Development
  • WordPress Plugins
  • Home
  • Passphrase Generator
  • Password Generator
  • About
  • Contact

PHP’s in_array() vs. jQuery’s inArray()

October 6, 2010 by Josh Hartman

This one stumped me for a bit when i was trying to use jQuery to populate checkboxes with a list of items pulled from a database using PHP.

The fact of the matter is that PHP’s in_array() returns a boolean whereas jQuery’s inArray() returns the index of the matching element, or if the element is not found it will return -1 or undefined, depending on the browser.

Problem

If you are used to using PHP like me jQuery’s inArray() can give you a headache when you are using the returned value of the function in an if-else condition. This is because -1 evaluates as true, when you really want it to evaluate as false.

Solution

Make it so that your if-else condition checks for a value >=0 (greater than or equal to zero). Since array’s don’t have negative indexes you’re safe doing it this way.

What did i learn from this? When working with a new function check the documentation for what type of data it will return.

jQuery.inArray Documentation

Example


Filed Under: Web Development Tagged With: in_array, inarray, jquery, php

Connect

  • Facebook
  • GitHub
  • RSS
  • Twitter
  • YouTube

Recent Posts

  • How to Permanently Remove the “Learn about this picture” Spotlight Wallpaper Icon From Your Windows Desktop
  • How to Quickly Test a Fax Machine
  • Extremely Useful Applications for Web Development and IT Tasks

Tags

automatic benchmark bigint class composer css embed escape event font function gzip helper htaccess html htmlspecialchars image increment javascript jquery list magento media mysql number observer opencart order output photo php profiling random redirect rijndael software text type ubuntu url windows windows 7 wordpress xampp xss

Blogroll

  • CodeIgniter
  • Fusion Forward
  • jQuery
  • Nettuts+
  • Smashing Magazine

© 2025 WarpConduit Computing. All Rights Reserved.