3v4l.org

run code in 300+ PHP versions simultaneously
<?php $haystack = [-6, 0, 5, 10, 11, 12, 20]; $needles = [0, 3, 14, -3]; function getNearest($needle, $haystack) { if (!$haystack) { throw new Exception('empty haystack'); } $bestDistance = PHP_INT_MAX; foreach ($haystack as $value) { if ($value === $needle) { return $needle; } $distance = abs($value - $needle); if ($distance < $bestDistance) { $bestDistance = $distance; $keep = $value; } } return $keep ?? $value; // coalesc to silence potential IDE complaint } foreach ($needles as $needle) { // each test case echo "$needle -> " . getNearest($needle, $haystack) . "\n"; }
Output for git.master, git.master_jit, rfc.property-hooks
0 -> 0 3 -> 5 14 -> 12 -3 -> -6

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
76.05 ms | 405 KiB | 5 Q