Solved

Randomly select x elements from an array

Posted on 2010-11-22
5
447 Views
Last Modified: 2012-05-10
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
Comment
Question by:interclubs
  • 2
  • 2
5 Comments
 
LVL 20

Expert Comment

by:DVation191
ID: 34190086
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
 
LVL 13

Accepted Solution

by:
dsmile earned 500 total points
ID: 34190281
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
 

Author Closing Comment

by:interclubs
ID: 34190497
nice.
0
 
LVL 20

Expert Comment

by:DVation191
ID: 34190561
Just curious for my own future reference...what was wrong with my solution?
0
 

Author Comment

by:interclubs
ID: 34190606
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question