-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
61 lines (48 loc) · 1.41 KB
/
functions.php
File metadata and controls
61 lines (48 loc) · 1.41 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
// functions.php
function fetchXkcdComic($comicId) {
$url = "https://xkcd.com/{$comicId}/info.0.json";
$json = @file_get_contents($url);
if ($json === FALSE) {
return null;
}
return json_decode($json, true);
}
function fetchRandomXkcdComic() {
// Latest known comic ID (as per your requirement)
$maxComicId = 3104;
$randomId = rand(1, $maxComicId);
// Try to fetch the random comic
$comic = fetchXkcdComic($randomId);
// If comic doesn't exist (unlikely but possible), try again
$attempts = 0;
while ($comic === null && $attempts < 5) {
$randomId = rand(1, $maxComicId);
$comic = fetchXkcdComic($randomId);
$attempts++;
}
return $comic ?: null;
}
function fetchMultipleXkcdComics($startId, $count = 9) {
$comics = [];
$currentId = $startId;
$attempts = 0;
$maxAttempts = $count * 2; // Prevent infinite loops
while (count($comics) < $count && $attempts < $maxAttempts) {
$comic = fetchXkcdComic($currentId);
if ($comic !== null) {
$comics[] = $comic;
$currentId--;
} else {
// If comic doesn't exist, try the previous one
$currentId--;
}
$attempts++;
// Don't go below comic #1
if ($currentId < 1) {
break;
}
}
return $comics;
}
?>