3v4l.org

run code in 500+ PHP versions simultaneously
<?php function hasLoop($head) { $slow = $head; $fast = $head; while ($fast !== null && $fast->next !== null) { $slow = $slow->next; $fast = $fast->next->next; if ($slow === $fast) { return true; } } return false; } // example usage class Node { public $data; public $next; public function __construct($data) { $this->data = $data; $this->next = null; } } $a = new Node(1); $b = new Node(2); $c = new Node(3); $d = new Node(4); $a->next = $b; $b->next = $c; $c->next = $d; var_dump(hasLoop($a)); // false $d->next = $b; var_dump(hasLoop($a)); // true
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
bool(false) bool(true)

preferences:
78.19 ms | 1110 KiB | 4 Q