Monday 3 September 2018

PHP sort table (loading database values) from the shortest to the longest

I have next code:

<select>
    <?php foreach ($values as $info) { ?>
      <option value="<?php echo $info['id'] ?>" <?php echo $value == $info['id'] ? 'selected="selected"' : '' ?>><?php echo $info['text'] ?></option>
    <?php } ?>
  </select>

i loading values from database! And have next results:
    <option value="1">Jacksonville (Florida)</option>
    <option value="2">Florida reg.</option>
    <option value="3">Florentia</option>
    <option value="9999">Florida</option>
    <option value="5">Miami (Florida)</option>

how to do: on the top were the shortest results for 'text':
Florida
Florentia
Florida reg.
Miami (Florida)
Jacksonville (Florida)
        <option value="9999">Florida</option>
        <option value="3">Florentia</option>
        <option value="2">Florida reg.</option>
        <option value="5">Miami (Florida)</option>
        <option value="1">Jacksonville (Florida)</option>

Thanks

You can use usort, as answered here in another question.
function sort($a,$b){
    return strlen($b)-strlen($a);
}

usort($array,'sort');

0 comments:

Post a Comment