Jump to content

return the closest numbers


joecooper

Recommended Posts

i have a list of resolutions, and i want the code to be able to find which one is the closest.

 

example of what im looking for:

$resolution could equal any 2 numbers in ####x#### format

eg 800x640, and the code needs to be able to choose which one is closest to that, so should return: 1024x768

 

the list i have is:

1920x1200

1680x1050

1440x900

1280x800

 

1600x1200

1280x960

1024x768

 

1280x1024

 

 

Link to comment
https://forums.phpfreaks.com/topic/64137-return-the-closest-numbers/
Share on other sites

try

<?php
function closest ($res)
{
    $res_array = array (
                '1920x1200',
                '1680x1050',
                '1440x900' ,
                '1280x800' ,
                '1600x1200',
                '1280x960' ,
                '1024x768' ,
                '1280x1024'
            );
            
    $diff = 9999;
    $result = '';
    list ($w, $h) = explode ('x', $res);
    foreach ($res_array as $str)
    {
        list ($w2, $h2) = explode ('x', $str);
        $d = abs($w2-$w) + abs($h2-$h);
        if ($d < $diff)
        {
            $result = $str;
            $diff = $d;
        }
    }
    return $result;        
}

echo closest('800x640');
?>

<?php

session_start();

require('db.php');

 

 

 

function closest ($res)

{

    $res_array = array (

                '1920x1200',

                '1680x1050',

                '1440x900' ,

                '1280x800' ,

                '1600x1200',

                '1280x960' ,

                '1024x768' ,

                '1280x1024'

            );

           

    $diff = 9999;

    $result = '';

    list ($w, $h) = explode ('x', $res);

    foreach ($res_array as $str)

    {

        list ($w2, $h2) = explode ('x', $str);

        $d = abs($w2-$w) + abs($h2-$h);

        if ($d < $diff)

        {

            $result = $str;

            $diff = $d;

        }

    }

    return $result;       

}

 

$resolution=($_GET['rez']);

$resolution=closest('$resolution');

die($resolution);

?>

 

this always seems to return 1024x768 when i access the URL with http://joeyjoe.co.uk/wallpaper/getpaper.php?how=random&rez=1680x1050

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.