Randomly extract some elements from the PHP array _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Randomly extract some elements from the PHP array. The method to randomly extract some elements is simple. you only need to use array_rand and range to implement this function, if you just extract an element, you can directly use mt_rand and then grow into a random number to randomly extract some elements. This function is easy to implement, as long as you use array_rand and range, if you just extract an element, you can directly use mt_rand and then grow into a random number length that does not exceed the length of the array.

Below I will provide you with several methods for your reference.


Method -:

The code is as follows:

$ Arr = range (1, 10, 1 );

$ Newarr = array_rand ($ arr, 6); // Obtain the keys in the six arrays at random.

$ NewArr = array_flip ($ newarr); // key-value interchange

$ Arr3 = array_diff_key ($ arr, $ newArr); // obtain the same key

$ Arr1 = array_diff_key ($ arr, $ arr3); // obtain the same key

Print_r ($ arr1 );

Result: array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [5] => 6 [9] => 10)

Method 2:

The code is as follows:

$ Arr = range (1, 10, 1 );

$ Newarr = array_rand ($ arr, 6); // Obtain the keys in the six arrays at random.

$ ArrNew = array ();

Foreach ($ newarr as $ k => $ v)
{
$ ArrNew [$ v] = $ arr [$ v];
}

Print_r ($ ArrNew );

Result: array ([1] => 2 [2] => 3 [3] => 4 [4] => 5 [6] => 7 [7] => 8)

Method 3: This method does not retain the key name for your reference.

The code is as follows:

$ Arr = range (1, 10, 1 );

Shuffle ($ arr); // disrupt the array

$ Newarr = array_splice ($ arr, 0, 6 );

Print_r ($ newarr );

Result: array ([0] => 7 [1] => 4 [2] => 2 [3] => 10 [4] => 9 [5] => 6)

...

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.