Find First Repeated Number in Array Using fn Function

PHOTO EMBED

Sat Jul 26 2025 16:56:35 GMT+0000 (Coordinated Universal Time)

Saved by @Samuel88 #php

<?php

function findFirstDuplicate($arr) {
    $seen = [];
    foreach ($arr as $num) {
        if (isset($seen[$num])) {
            return $num;
        }
        $seen[$num] = true;
    }
    return null;
}

$fn = fn($arr) => findFirstDuplicate($arr);

echo $fn([2, 5, 1, 2, 3, 5]); // Output: 2
content_copyCOPY

The `fn` function finds the first repeated number in an array. It takes one parameter: - `$arr`: a list of integers. It uses an associative array called `$seen` to store found values. It loops through `$arr`: - If a number exists in `$seen`, it returns that number. - If not, it adds the number to `$seen`. If no number repeats, the function returns `null`. This runs in linear time. Each check and insert uses constant time.

https://flatcoding.com/tutorials/php/arrow-functions/