Solved

array_rand() question

Posted on 2013-12-11
4
203 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 110

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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

707 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