Search code examples
phparrayssubstringgrouping

Group array values by trailing letters


I have an array like so (generated from an API):

    [18] => 3107SkincareL
    [19] => 3INAL
    [20] => 3M
    [21] => 3rdRockEssentialsFL
    [22] => 4BeautyGroupL
    [23] => 4EVERMAGICCOSMETICSL

As you can see, some of the entries feature a trailing "L" or "FL". I would like to sort everything ending with "L" into a group and everything that ends with "FL" into a group and everything else in another group.


Solution

  • This should be what you are looking for:

    <?php
    $input = [
      18 => "3107SkincareL", 
      19 => "3INAL", 
      20 => "3M", 
      21 => "3rdRockEssentialsFL", 
      22 => "4BeautyGroupL", 
      23 => "4EVERMAGICCOSMETICSL", 
    ];
    $output = [];
    array_walk($input, function($entry) use (&$output) {
        if ("FL" == substr($entry, -2)) {
            $output["FL"][] = $entry;
        } else if ("L" == substr($entry, -1)) {
            $output["L"][] = $entry;
        } else {
            $output["?"][] = $entry;        
        }
    });
    print_r($output);
    

    The output obviously is:

    Array
    (
        [L] => Array
            (
                [0] => 3107SkincareL
                [1] => 3INAL
                [2] => 4BeautyGroupL
                [3] => 4EVERMAGICCOSMETICSL
            )
        [FL] => Array
            (
                [0] => 3rdRockEssentialsFL
            )
        [?] => Array
            (
                [0] => 3M
            )
    )