0

I have here my php code and txt file. I want to display 6 lines in .txt file randomly at the output of php. How can i do it. I try my code but it only display the first 6 lines. Thanks!

Php:

require_once "config.php";
$txt_file    = file_get_contents($database);
$rows        = explode("\n", $txt_file);
array_shift($rows);
$i = 0;
foreach($rows as $row => $data)
{
    $row_data = explode('&id=', $data);
    $info[$row]['name']   = $row_data[0];
    $info[$row]['id']      = $row_data[1];

    $name = $info[$row]['name'];
    $id = $info[$row]['id'];
    echo $name."<BR>";
    echo $id."<BR><BR>";

    if (++$i == "6") break;
}

Txt file:

ABC&id=1
DEF&id=2
GHI&id=3
user2651946
  • 21
  • 1
  • 8
  • Try shuffling the array and then run the loop? http://php.net/manual/en/function.shuffle.php – Salman Aug 05 '13 at 05:57

1 Answers1

0
<?
// read file content into array
// http://fi2.php.net/file
    $txt_file    = file($database);

// pick six elements randomly
// http://fi2.php.net/array_rand    

foreach( array_rand($txt_file, count($txt_file)>6 ? 6 : count($txt_file)) as $row => $data)
{
    $row_data = explode('&id=', $data);
    $info[$row]['name']   = $row_data[0];
    $info[$row]['id']      = $row_data[1];

    $name = $info[$row]['name'];
    $id = $info[$row]['id'];
    echo $name."<BR>";
    echo $id."<BR><BR>";

}
?>
iiro
  • 3,132
  • 1
  • 19
  • 22
  • Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in – user2651946 Aug 05 '13 at 05:55