3v4l.org

run code in 500+ PHP versions simultaneously
<?php function showCell($cell, $isHeader, $selectedTitle) { echo '<td>'; if ($selectedTitle || $isHeader) { echo htmlspecialchars($cell); } else { echo sprintf('<a href="?title=%1$s">%1$s</a>', htmlspecialchars($cell)); } echo '</td>', PHP_EOL; } function showRow($cellsToShow, $isHeader, $selectedTitle) { if ($isHeader) { echo '<thead>', PHP_EOL; } echo '<tr>', PHP_EOL; foreach ($cellsToShow as $cell) { showCell($cell, $isHeader, $selectedTitle); } echo '</tr>', PHP_EOL; if ($isHeader) { echo '</thead>', PHP_EOL; } } function showTable($handle, $selectedTitle) { $idx = 0; echo '<table>', PHP_EOL; while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) { // If we're on the first row which holds titles, always show. // Also, if the user selected a title, and it matches this row's title, show it. if(0 !== $idx && $selectedTitle && $row[0] !== $selectedTitle){ continue; } // cellsToShow is always an array. If we're showing based on a selection, it is everything. // Otherwise, it will be an array of just the first cell. This last seems weird, but it // allows the showRow method to not concern itself with higher level logic. $cellsToShow = $selectedTitle ? $row : [$row[0]]; showRow($cellsToShow, $idx++ === 0, $selectedTitle); } echo '</table>', PHP_EOL; } // Mock a CSV file in memory for demo purposes $handle = fopen('php://memory', 'rb+'); fwrite($handle, "Title,Author,Year\nBook 1,Alice,2020\nBook 2,Bob,2019\nBook 3,Charlie,1980"); rewind($handle); // Grab the title from the query string, default to null if not found $selectedTitle = $_GET['title'] ?? null; showTable($handle, $selectedTitle); fclose($handle);

preferences:
84.33 ms | 1166 KiB | 5 Q