Twifty
Twifty

Reputation: 3378

Find the next highest array key

Is there a one liner for finding an integer key equal to or greater than a given index? To make things clear, here's an example of an array I'm working with.

array( 4294967295 => 'LONGTEXT'
     , 16777215   => 'MEDIUMTEXT'
     , 65535      => 'TEXT'
     , 255        => 'TINYTEXT' );

As some of you may recognize, these are MySQL column definition types. Let's say I'm given an integer 500, how can I quickly/compactly find the next key of 65535 which maps to 'TEXT'?

Currently I iterate the array using foreach (hence highest values first) and track the last key. But, due to the number of arrays and data types I'm dealing with, the function has become bloated.

Upvotes: 0

Views: 141

Answers (1)

George Brighton
George Brighton

Reputation: 5151

This is compact and should work:

$sizes = array_filter(array_keys($array), function($element) use ($size) { return $element >= $size; });
$array[array_pop($sizes)];

This will emit an undefined index error if no type large enough exists in $array. I really wouldn't consider it optimal - the best solution is rarely the shortest possible.

Consider using something like this, which is more robust:

function getType(array $types, $desiredSize) { // $types should be sorted by key asc
    foreach($array as $length => $type) {
        if($length >= $desiredSize) {
            return $type;
        }
    }

    return null; // no type large enough
}

$types = array(
        4294967295 => 'LONGTEXT',
        16777215 => 'MEDIUMTEXT',
        65535 => 'TEXT',
        255 => 'TINYTEXT');
ksort($types); // or hardcode it in asc order

echo getType($types, 500); // TEXT

Upvotes: 2

Related Questions