0

I am trying to create a new array from an existing one with a random number of records between 2 and 10, I have this so far

//Select a random number
$random_number = (rand(2,10));

// Setup an array of names
$names = array("john", "joe", "simon", "peter", "paul");

// Create new array
$random_field_names = array_rand($names, $random_number);

print_r($random_field_names);

This gives me an array that looks like this

Array
(
    [0] => 0
    [1] => 10
    [2] => 11
)

Where am I going wrong?

1
  • Can you add an example of what you want the desired output to be? I'm a little confused about what you are trying to do. Commented Nov 24, 2016 at 21:26

3 Answers 3

2

Use the key to get the value you want :

//Select a random number
$random_number = (rand(2,10));

// Setup an array of names
$names = array("john", "joe", "simon", "peter", "paul");

// Create new array
$random_field_names = array_rand($names, $random_number);

print_r($names[$random_field_names]);
Sign up to request clarification or add additional context in comments.

Comments

1

The description of array_rand explains why you don't get the names (I stress in bold):

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

You seem to want the values. That you can achieve like this:

 array_intersect_key($names,  array_flip(array_rand($names, $random_number)));

Also make sure your random number is not greater than the array size:

$random_number = rand(2,5);
$names = array("john", "joe", "simon", "peter", "paul");
$result = array_intersect_key($names,  array_flip(array_rand($names, $random_number)));
print_r ($result);  

Note that the result maintains the original keys. If you want to renumber the keys to get an indexed array starting with index 0, then apply array_values to the result:

$result = array_values(array_intersect_key($names,  array_flip(array_rand($names, $random_number))));

3 Comments

When I try and extract an item from the new array using $result[1] I get no results, is this something to do with the way the new array is constructed?
Indeed, the result array maintains the original keys. See addition to my answer.
Thank you very much, makes much more sense now
1
  1. syntax error on line 5 - missing quote after "simon
  2. array_rand() returns random key(s), not values
  3. rand(2,10) won't work in all cases as there are only 5 entries in the array; from PHP docs: Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.

If you want to randomize the entire array, use shuffle().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.