---
layout: page
title: "JavaScript count function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/count:375
- /functions/view/count
- /functions/view/375
- /functions/count:375
- /functions/375
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's count

{% codeblock array/count.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/count.js raw on github %}
function count (mixed_var, mode) {
  // From: http://phpjs.org/functions
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +      input by: Waldo Malqui Silva
  // +   bugfixed by: Soren Hansen
  // +      input by: merabi
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Olivier Louvignes (http://mg-crea.com/)
  // *     example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE');
  // *     returns 1: 6
  // *     example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
  // *     returns 2: 6
  var key, cnt = 0;

  if (mixed_var === null || typeof mixed_var === 'undefined') {
    return 0;
  } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object) {
    return 1;
  }

  if (mode === 'COUNT_RECURSIVE') {
    mode = 1;
  }
  if (mode != 1) {
    mode = 0;
  }

  for (key in mixed_var) {
    if (mixed_var.hasOwnProperty(key)) {
      cnt++;
      if (mode == 1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object)) {
        cnt += this.count(mixed_var[key], 1);
      }
    }
  }

  return cnt;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/count.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/count.js)

### Example 1
This code
{% codeblock lang:js example %}
count([[0,0],[0,-4]], 'COUNT_RECURSIVE');
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
6
{% endcodeblock %}

### Example 2
This code
{% codeblock lang:js example %}
count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
6
{% endcodeblock %}


### Other PHP functions in the array extension
{% render_partial _includes/custom/array.html %}
