UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

105 lines (89 loc) 2.84 kB
--- layout: page title: "JavaScript in_array function" comments: true sharing: true footer: true alias: - /functions/view/in_array:432 - /functions/view/in_array - /functions/view/432 - /functions/in_array:432 - /functions/432 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's in_array {% codeblock array/in_array.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/in_array.js raw on github %} function in_array (needle, haystack, argStrict) { // From: http://phpjs.org/functions // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: vlado houba // + input by: Billy // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']); // * returns 1: true // * example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'}); // * returns 2: false // * example 3: in_array(1, ['1', '2', '3']); // * returns 3: true // * example 3: in_array(1, ['1', '2', '3'], false); // * returns 3: true // * example 4: in_array(1, ['1', '2', '3'], true); // * returns 4: false var key = '', strict = !! argStrict; if (strict) { for (key in haystack) { if (haystack[key] === needle) { return true; } } } else { for (key in haystack) { if (haystack[key] == needle) { return true; } } } return false; } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/in_array.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/array/in_array.js) ### Example 1 This code {% codeblock lang:js example %} in_array('van', ['Kevin', 'van', 'Zonneveld']); {% endcodeblock %} Should return {% codeblock lang:js returns %} true {% endcodeblock %} ### Example 2 This code {% codeblock lang:js example %} in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'}); {% endcodeblock %} Should return {% codeblock lang:js returns %} false {% endcodeblock %} ### Example 3 This code {% codeblock lang:js example %} in_array(1, ['1', '2', '3']); in_array(1, ['1', '2', '3'], false); {% endcodeblock %} Should return {% codeblock lang:js returns %} true true {% endcodeblock %} ### Other PHP functions in the array extension {% render_partial _includes/custom/array.html %}