Fork me on GitHub

Learn how to do it in JavaScript. Explore boundaries porting languages. Enjoy functions that turn out to be useful.

Here’s what a JavaScript equivalent for PHP’s array_keys looks like.

function array_keys (input, search_value, argStrict) {
  //  discuss at: http://phpjs.org/functions/array_keys/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //    input by: Brett Zamir (http://brett-zamir.me)
  //    input by: P
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  // improved by: jd
  // improved by: Brett Zamir (http://brett-zamir.me)
  //   example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
  //   returns 1: {0: 'firstname', 1: 'surname'}

  var search = typeof search_value !== 'undefined',
    tmp_arr = [],
    strict = !!argStrict,
    include = true,
    key = ''

  if (input && typeof input === 'object' && input.change_key_case) {
    // Duck-type check for our own array()-created PHPJS_Array
    return input.keys(search_value, argStrict)
  }

  for (key in input) {
    if (input.hasOwnProperty(key)) {
      include = true
      if (search) {
        if (strict && input[key] !== search_value) {
          include = false
        } else if (input[key] != search_value) {
          include = false
        }
      }

      if (include) {
        tmp_arr[tmp_arr.length] = key
      }
    }
  }

  return tmp_arr
}
View on GitHub Edit on GitHub Source on GitHub

PHP arrays and JavaScript

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest we can get to this hashtable-like data structure without rolling our own. While many JavaScript implementations preserve the order of object properties, the ECMAScript Language Specification explicitly states that:

The mechanics and order of enumerating the properties is not specified.

So don't use this for anything serious if you rely on the order to be consistent accross platforms.

A community initiative

php.js offers community built functions and goes by the McDonald’s Theory. We’ll put online functions that aren't perfect, in the hopes to spark better contributions. Do you have one? You can directly edit this file on GitHub, this will create a Pull Request that the core team can review, and merge into our codebase.

This way of working also means that we don't offer any production guarantees, and recommend to use php.js inspiration and learning purposes only.

Example 1

array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
Should return:
{0: 'firstname', 1: 'surname'}

« More array functions