Four methods to randomly retrieve a piece of data from the PHP file _ PHP Tutorial

Source: Internet
Author: User
You can randomly retrieve a piece of data from the PHP file in four ways. This article describes how to randomly retrieve a data instance in the PHP file. I hope this tutorial will be helpful to you. The code is as follows: Copy the code? First php method: $ lin this article will introduce you to randomly retrieve a data instance from the php file. I hope this tutorial will be helpful to you.
The code is as follows:
// Method 1:
$ Line = getrandline1('test.txt ');
Function getrandline1 ($ filename)
{
$ Linenum = 0;
$ Fh = fopen ($ filename, 'r ');
While (! Feof ($ fh ))
{
If ($ rowcontents = fgets ($ fh ))
{
$ Linenum ++;
$ Contens [] = $ rowcontents;
}
}
$ Randline = mt_rand (0, $ linenum-1 );
$ Line = $ contens [$ randline];
Fclose ($ fh );
Return $ line;
}

// Method 2:
$ Line = getrandline2('test.txt ');
Function getrandline2 ($ filename)
{
$ Contents = file('test.txt ');
$ Linenum = count ($ contents );
$ Randline = mt_rand (0, $ linenum-1 );
$ Line = $ contents [$ randline];
Return $ line;
}

// Method 3:
$ Line = getrandline3('test.txt ');
Function getrandline3 ($ filename)
{
$ Contents = file('test.txt ');
Shuffle ($ contents );
Return $ contents [0];
}

// Method 4:
$ Line = getrandline4('test.txt ');
Function getrandline4 ($ filename)
{
$ Linenum = 0;
$ Fh = fopen ($ filename, 'r ');
While (! Feof ($ fh ))
{
If ($ linecontents = fgets ($ fh ))
{
$ Linenum ++;
$ Randint = (mt_rand (1, 1000000 * $ linenum)-1)/1000000 );
If ($ randint <1)
{
$ Line = $ linecontents;
}
}
}
Fclose ($ fh );
Return $ line;
}
?>

The examples file randomly retrieves a data instance. I hope this tutorial will help you. The code is as follows? Php // Method 1: $ lin...

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.