Home >Backend Development >PHP Tutorial >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:
if ($.inArray('value', array) !== -1) { // Value found in the array }
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!