Home >Backend Development >PHP Tutorial >Is there a JavaScript equivalent to PHP's in_array()?

Is there a JavaScript equivalent to PHP's in_array()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 08:17:01659browse

Is there a JavaScript equivalent to PHP's in_array()?

JavaScript Equivalent to PHP's in_array()

JavaScript does not have an exact equivalent to PHP's in_array() function, which checks if one array contains a specific value from another array. However, several third-party libraries come with utility functions that provide similar functionality.

For Basic Value Comparison

For simple value comparison, you can use one of these libraries:

  • jQuery's jQuery.inArray(): Checks if a value exists in an array efficiently.
if ($.inArray('value', array) !== -1) {
  // Value found in the array
}
  • Prototype's Array.indexOf(): Returns the index of an array element that matches the specified value.
if (array.indexOf('value') !== -1) {
  // Value found in the array
}

For Array Comparison

If you need to check if one array is contained within another, you can use this custom function:

function inArray(needle, haystack) {
  return haystack.some(function(value) {
    return value.every(function(item) {
      return needle.includes(item);
    });
  });
}

This function implements the behavior of PHP's in_array(), where it returns true if the values of the needle array are all contained within one of the haystack array's subarrays.

Example

var needle = ['p', 'h'];
var haystack = [['p', 'h'], ['p', 'r'], 'o'];

if (inArray(needle, haystack)) {
  // Needle array is contained in one of the subarrays of haystack
}

The above is the detailed content of Is there a JavaScript equivalent to PHP's in_array()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn