/
random_movie.php
47 lines (40 loc) · 1.07 KB
/
random_movie.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
$inputFile = 'movies.txt';
$outputFile = 'sorted_movies.txt';
/**
* Read in a file, return contents as an array
**/
function readLines($inputFile)
{
$filename = $inputFile;
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
$contentsArray = explode("\n", $contents);
fclose($handle)
return $contentsArray;
}
/**
* Write contents of an array to a file
**/
function writeLines($outputFile, $moviesArray)
{
$filename = $outputFile;
$handle = fopen($filename, 'w+');
$moviesList = implode("\n", $moviesArray);
fwrite($handle, $moviesList);
fclose($handle)
}
// /**
// * Pick a random movie from an array
// **/
function randomMovie($movies)
{
$randomKey = array_rand($movies);
return $movies[$randomKey];
}
$movies = readLines($inputFile); // movies is an unsorted array at this point
$randomMovie = randomMovie($movies);
echo "Let's watch " . $randomMovie . "!\n";
echo "But " . $randomMovie . " really sucks!\n";
sort($movies); // Alphabetizes the movies array before writing it to a new file:
writeLines($outputFile, $movies);