Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull random line from TXT file as string

Tags:

text

php

random

I'm currently using the code below to try and read a random line from random.txt and pass it as $data, however it comes back empty. Each string has its own line, am I missing something here? Shouldn't this work? If not how can I get a random line from my text file and use it as my $data string?

$f_contents = file("random.txt");
$line = $f_contents[array_rand($f_contents)];
$data = $line;

Solved - Bad CHMOD Thought I had double checked it, sorry to post a question.

like image 370
Ryan Cooper Avatar asked May 05 '11 21:05

Ryan Cooper


People also ask

How do you get a line from a text file in Python?

Use readlines() to Read the range of line from the File The readlines() method reads all lines from a file and stores it in a list. You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python.

How do you generate a random string in Python?

We can Generate Random Strings and Passwords in Python using secrets. choice(). For Cryptographically more secure random numbers, this function of the secret module can be used as its internal algorithm is framed in a way to generate less predictable random numbers.


1 Answers

Your code looks correct, but you can try it this way too:

<?php
    $f_contents = file("random.txt"); 
    $line = $f_contents[rand(0, count($f_contents) - 1)];
?>
like image 135
Sitnik Avatar answered Sep 16 '22 13:09

Sitnik