WarpConduit Computing

  • Quick Tips
  • Web Design & Development
  • Graphic Design
  • Home
  • WordPress Plugins
  • 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

<script>
	var myArray = ['a', 'b', 'c'];
	document.write(jQuery.inArray('a',myArray) + '<br/>'); //returns '0'
	document.write(jQuery.inArray('b',myArray) + '<br/>'); //returns '1'
	document.write(jQuery.inArray('c',myArray) + '<br/>'); //returns '2'
	document.write(jQuery.inArray('d',myArray) + '<br/>'); //returns '-1' or undefined
</script>

<script> var myArray = ['a', 'b', 'c']; document.write(jQuery.inArray('a',myArray) + '<br/>'); //returns '0' document.write(jQuery.inArray('b',myArray) + '<br/>'); //returns '1' document.write(jQuery.inArray('c',myArray) + '<br/>'); //returns '2' document.write(jQuery.inArray('d',myArray) + '<br/>'); //returns '-1' or undefined </script>

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

Connect

  • Facebook
  • GitHub
  • RSS
  • Twitter
  • YouTube

Recent Posts

  • Extremely Useful Applications for Web Development and IT Tasks
  • Installing BookStack Wiki on cPanel Shared Hosting
  • Media (MIME) Type Reference List

Tags

automatic base64 benchmark cache counter css deflate email font gzip htaccess html image inarray increment inline images in_array javascript jquery link list magento mailto menu metadot mysql number obfuscation opencart operating system order php random redirect rewriterule slashes software timestamp ubuntu unix upgrade url windows windows 7 wordpress

Blogroll

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

© 2022 WarpConduit Computing. All Rights Reserved.