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

{% codeblock array/array_rand.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/array_rand.js raw on github %}
function array_rand (input, num_req) {
  // From: http://phpjs.org/functions
  // +   original by: Waldo Malqui Silva
  // *     example 1: array_rand( ['Kevin'], 1 );
  // *     returns 1: 0
  var indexes = [];
  var ticks = num_req || 1;
  var checkDuplicate = function (input, value) {
    var exist = false,
      index = 0,
      il = input.length;
    while (index < il) {
      if (input[index] === value) {
        exist = true;
        break;
      }
      index++;
    }
    return exist;
  };

  if (Object.prototype.toString.call(input) === '[object Array]' && ticks <= input.length) {
    while (true) {
      var rand = Math.floor((Math.random() * input.length));
      if (indexes.length === ticks) {
        break;
      }
      if (!checkDuplicate(indexes, rand)) {
        indexes.push(rand);
      }
    }
  } else {
    indexes = null;
  }

  return ((ticks == 1) ? indexes.join() : indexes);
}
{% endcodeblock %}

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

### Example 1
This code
{% codeblock lang:js example %}
array_rand( ['Kevin'], 1 );
{% endcodeblock %}

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


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