[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 455
  • Last Modified:

Randomly select x elements from an array

I have an array, like:
$array = array('dog','cat','sam','puppy','mouse','coke');

How can I create a new array, that has only x number of elements, randomly chosen from $array?
0
interclubs
Asked:
interclubs
  • 2
  • 2
1 Solution
 
DVation191Commented:
http://php.net/manual/en/function.array-rand.php

$x = 3;
$array = array('dog','cat','sam','puppy','mouse','coke');
$rand_keys = array_rand($array , $x);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
echo $input[$rand_keys[3]] . "\n";
0
 
dsmileCommented:
Use shuffle() to make array randomly ordered, and then pick up x element(s) to create new array by using array_splice()
<?php
$array = array('dog','cat','sam','puppy','mouse','coke');

//reorder the array randomly
shuffle($array);

//create new array
$n = 3; // change this to x number you want
$newarray = array_splice($array, $n);

print_r($newarray);

Open in new window

0
 
interclubsAuthor Commented:
nice.
0
 
DVation191Commented:
Just curious for my own future reference...what was wrong with my solution?
0
 
interclubsAuthor Commented:
It didn't work. I think you meant:

$x = 3;
$array = array('dog','cat','sam','puppy','mouse','coke');
$rand_keys = array_rand($array , $x);
echo $array[$rand_keys[0]] . "\n";
echo $array[$rand_keys[1]] . "\n";
echo $array[$rand_keys[2]] . "\n";

(Changed parts in bold). That made it work, but it still wasn't giving me a new array, it was just randomly picking elements from an array.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now