Solved

array_rand() question

Posted on 2013-12-11
4
199 Views
Last Modified: 2013-12-12
I want to randomly choose items in my array and keep their values.

when I run this on my array
print_r($array_local_ids);

echo "</br>";

print_r(array_rand($array_local_ids,2));

Open in new window


it prints this
Array ( [0] => 175 [1] => 174 [2] => 177 [3] => 179 [4] => 176 )
Array ( [0] => 2 [1] => 4 )

i want the values of the first array in my random array not the keys of the first array.
0
Comment
Question by:Luey
  • 2
4 Comments
 
LVL 83

Accepted Solution

by:
Dave Baldwin earned 500 total points
ID: 39712685
The keys is what it returns.  http://us.php.net/manual/en/function.array-rand.php  It does not change the array.  The idea is that you use the keys in a 'foreach' to 'randomly' access the original array.
0
 

Author Comment

by:Luey
ID: 39712730
ok yep done that before.  I want them back in an array so I can use them in sql so I quess I have to create that new array in foreach.  Is that right?
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39712803
That's right.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39713902
If you want all of the values in random order, you can copy the array and use shuffle().  If you want to choose one element at random, you can use end() after shuffle().
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying 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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

821 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