0

I have a PHP array that looks like this

$alphabet= array('a','b','c')

$alphabet is a input i need a result like $result

Expected output:

$result= array(
  [0]=> "a"
  [1]=> "b"
  [2]=> "c"
  [3]=> "ab"
  [4]=> "ac"
  [5]=> "bc"
  [6]=> "abc"
)

Note: here, I would not like sorting to use. Thanks!

Sathish
  • 2,440
  • 1
  • 11
  • 27

1 Answers1

0

Use usort and costum sort function:

$array = array("a", "bc", "bb", "aa", "cc", "bb");

function sortByValueLength($a, $b)
{
    $aLength = mb_strlen($a, 'utf-8');
    $bLength = mb_strlen($b, 'utf-8');
    if ($aLength == $bLength) {
        return strcmp($a, $b);
    }

    return $aLength - $bLength;
}

usort($array, 'sortByValueLength');

var_export($array);

Example result here

sergio
  • 5,210
  • 7
  • 24
  • 46