Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

PHP-like in_array function in JavaScript

Monday, April 30th, 2018 by Servage

Recently I once more found myself in a situation where I really felt that I am a PHP-developer, more that a JavaScript-developer. Do you also find your self writing stuff like in_array() in JavaScript code? It happens often to me, that I take for granted in other languages, what I know and love in PHP. It also often takes quite a while to find a good alternative for missing functions in JavaScript, since Google often provides you with multiple options.

One of the common functins I miss in JavaScript from PHP is in fact the “in_array”-function. Luckily there is a splendid JavaScript snippet here:

function in_array (needle, haystack, argStrict) {
  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;
}

It’s really easy to use. Like you know the syntax from PHP:

var testarray = ['one','two','three'];
alert(in_array('one', testarray));
PHP-like in_array function in JavaScript, 3.9 out of 5 based on 8 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 comments (leave a comment)

With this in mind Ill take the opportunity to describe the architecture of Xenos a little..On the client side everything runs through Javascript. The most important class in there is one called screen which takes commands and generates JavaScript code which is returned by the action RPC after running the action to the client..The other big API there is game if.

.I am always amazed at the very nice features of JavaScript on the one hand and the very very bad features of it on the other side….Heres something I learned the other week that I find quite interesting eval vs. Heres what I wanted to achieve I was looking for a way to do some meta-programming with JavaScrip specifically prevent the problem that any variable you assign to but dont declare ends up as a member of the global object….The problem is that name lookup in JavaScript is quite peculiar.

Leave a comment

You must be logged in to post a comment.