PHP code that randomly extracts some elements from an array

Source: Internet
Author: User
  1. /**

  2. * Random extraction of array elements
  3. * Author:notuser
  4. * 2012-12-29
  5. */
  6. Class GetValues {
  7. Public Function Inputvalue ($inputArray) {
  8. $this->inputarray = $inputArray;
  9. }
  10. Public Function GetValue ($number) {
  11. $this->number = $number;
  12. for ($i = 0; $i < $this->number; $i + +) {
  13. $index = rand (0, COUNT ($this->inputarray)-1-$i);
  14. $getArray [$i] = $this->inputarray [$index];
  15. unset ($this->inputarray [$index]);
  16. for ($k = $index; $k < count ($this->inputarray)-1; $k + +) {
  17. $this->inputarray [$k] = $this->inputarray [$k + 1];
  18. }
  19. }
  20. Asort ($getArray); Sort from small to large, modify as needed
  21. return $getArray;
  22. }
  23. }

  24. Test code

  25. $keywords = Array (
  26. "We",
  27. "You,"
  28. They
  29. );
  30. $getValue =new getValues ();
  31. $getValue->inputvalue ($keywords);
  32. $key = $getValue->getvalue (1);//randomly extracting an element from an array
  33. Echo $key;
  34. ? >

Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.