Combining a PHP array with order from left to right

I have a PHP array that looks like

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

$ alphabet is the input, I need a result like $ result

Expected Result:

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

Note: here I would not want sorting to be used. Thank!

0
source share
1 answer

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);

Result here

0
source

Source: https://habr.com/ru/post/1758436/


All Articles