Explain Codes LogoExplain Codes Logo

Javascript equivalent of PHP's in_array()

javascript
polyfill
array-methods
browser-support
Alex KataevbyAlex Kataev·Feb 26, 2025
TLDR

If you're looking for an equivalent of PHP's in_array() in JavaScript, Array.includes() would be a straightforward solution to check whether an element exists in an array, as shown below.

const pets = ['cat', 'dog', 'bat']; const doesDogExist = pets.includes('dog'); // true, dog is definitely a part of the family!

In case you're dealing with older browsers like IE9 and below, go for Array.indexOf() which returns the first index at which the given element is found in the array, or -1 if not present.

const doesDogExist = pets.indexOf('dog') !== -1; // also true, Woof Woof Browser can find the dog too!

Older Browser Support

If your project needs to support older browsers, and you wish to have the PHP's in_array() equivalent function that still works with those elderlies, here's your polyfill for Array.includes().

if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement /*, fromIndex*/) { // This is serious stuff, unlike my Ex who wasn't serious at all. var O = Object(this); var len = parseInt(O.length, 10) || 0; if (len === 0) { return false; // Much like my search for love. 💔 } var n = parseInt(arguments[1], 10) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) { k = 0; } } var currentElement; while (k < len) { currentElement = O[k]; if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) { return true; // We found it! Like finding a missing sock from laundry. } k++; } return false; }; }

It ensures that includes() is available even in those internet dinosaurs.

If you want to go Pro: Deep Equality Check

Both includes and indexOf perform a shallow comparison meaning if you threw at them a chunk of complex data, they would sadly fail. Fret not, with a recursive arrayCompare function, you can have your own deep equality version.

function arrayCompare(value, array) { return array.some(function(element) { if (element === value) { return true; } if (typeof element === 'object' && typeof value === 'object') { return JSON.stringify(element) === JSON.stringify(value); } return false; }); } const aestheticColors = [{ color: 'red' }, { color: 'blue' }]; const isRedInFashion = arrayCompare({ color: 'red' }, aestheticColors); // true, red is in!

Visualising it with a Classic Example

Let's pretend we're at a book club with an array of books:

Book Club 📚: [JavaScript, Python, Ruby, Java]

When we're asking:

Is "JavaScript" on the book club shelf? 🤔

JavaScript provides includes() to verify:

const bookshelf = ['JavaScript', 'Python', 'Ruby', 'Java']; console.log(bookshelf.includes('JavaScript')); // true 🎉

Every JavaScript lover will agree:

📚➡️ "JavaScript"? ➡️ ✅ Yes, pages full of love!

Going Off-road: Manual Implementation

Sometimes we need to go the old-fashioned way. Despite the convenience of includes and indexOf, there could be scenarios where a custom manual implementation might be preferable:

  • Performance Intensive Situations: When dealing with an army of data, a custom function using for-loops or while-loops could be optimized better, kind of like creating a superhero with a special power!

  • Non-Primitive Mischief: If your mix includes objects, functions or arrays, they are complex and would need your coding skills to whip up a custom solution.

  • Extensible code: If you're laying down the infrastructure for a library or a framework, a custom in-array check function that fits nicely with your design might be your best bet.

Avoiding the Traps: Prototype Pollution

While adding custom methods, steer clear of extending the Array.prototype directly. It's a path leading to conflicts with libraries or curious bugs popping up in your codebase. So, instead of increasing your debugging time, define a utility function that acts as a savior!

function inArray(element, array) { return array.indexOf(element) > -1; } const favouriteLanguages = ['Python', 'JavaScript']; const isJavaScriptFavourite = inArray('JavaScript', favouriteLanguages); // Returns true, confirmed - JavaScript is a Fav!

Your global scope remains clean, and conflicts are avoided. A win-win!