How to randomize order of lines? [SOLVED]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

How to randomize order of lines? [SOLVED]

Post by tomfra »

There is one "keyword" file (keywords.txt)with this content:

keyword 1
keyword 2
keyword 3
keyword 4
keyword 5
keyword 6

I want to randomize the order of each of the "keywords" so that the output looks something like for example (file name: random_kws.txt):

keyword 2
keyword 1
keyword 4
keyword 3
keyword 6
keyword 5

I tried this code:

Code: Select all

<?php

function file_write_data($filename, $file_body, $chmod=0777, $mode='w')&#123;
  $handle = fopen($filename, $mode);
  fwrite($handle, $file_body);
  fclose($handle);
  chmod ($filename, $chmod);
 return $file_body;
&#125;

$keyword_file = 'keywords.txt'; 
$keywords = file_get_contents($keyword_file); 
$keywords = explode("\n", $keywords);
$lines_count = count($keywords);

for($n=0; $n<=$lines_count-1; $n++)&#123; 
  $random_kw = mt_rand(0, $lines_count-1); 
  $Terms = $keywords&#1111;$random_kw]; 
  $AllKeywords .= "$Terms\n"; 
&#125;

file_write_data('random_kws.txt', $AllKeywords, 0777);

$FileArr = file('random_kws.txt');

$FilteredArr = array("a\n\r", "\n\r", "\n\r", "b\n\r");
$FilteredArr = array_map('trim', $FileArr);
$FilteredArr = array_filter($FilteredArr);
$FilteredArr = array_unique($FilteredArr);
$FilteredArr = array_values($FilteredArr);
sort($FilteredArr);
reset($FilteredArr);

$kw_count = count($FilteredArr);
echo file_get_contents('random_kws.txt');


?>
This code does indeed randomize the order, but not properly. It lists some of the keywords multiple times while others not all. The point is, each of the keywords/lines should be in the random list, just in a random order on each script run.

Any ideas are welcome!

Tomas
Last edited by tomfra on Thu Feb 03, 2005 5:22 pm, edited 1 time in total.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

shuffle($keywords);
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Post by tomfra »

Thanks for the tip! It does indeed work. It looks like I will have to learn arrays beside regex... I am feeling a bit dumb now :oops:

Thanks again!

Tomas
Post Reply