Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to find minimum distance between two numbers in an array with PHP

1 Answer

0 votes
function MinDistance(&$arr, $number1, $number2) {
    $size = count($arr);

    $min_distance = PHP_INT_MAX;
    
    for ($i = 0; $i < $size; $i++) {
        for ($j = $i + 1; $j < $size; $j++) {
            if ($arr[$i] == $number1 && $arr[$j] == $number2 || 
                $arr[$i] == $number2 && $arr[$j] == $number1) {
                $min_distance = min($min_distance, abs($i - $j));
            }
        }
    }
    return $min_distance;
}
        
$arr = array(2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3);
        
echo MinDistance($arr, 3, 8);




/*
run:

2

*/

 



answered Aug 24, 2022 by avibootz

Related questions

...