phparraysgroupingstring-parsingdelimited

Group values of a flat array based on their leading substring


What I want the code below to do is loop through the $check_query array, find all the values that contain the word standard and push them into an array. I'd like to also do this for the strings that contain upgrade. Example $range_array should return ['standard-186', 'standard-184];

$check_query = ['standard-186', 'upgrade-186', 'standard-184', 'upgrade-184'];
$range_array = [];
$spec_array = [];

foreach($check_query as $value) {

    if (in_array("standard", $value)) {
        array_push($range_array, $value);
    }
    elseif (in_array("upgrade", $value)) {
        array_push($spec_array, $value);
    } else {
        // Nothing
    }
}

echo $range_array;
echo $spec_array;

Solution

  • This can be done in one line using array_filter()

    <?php
    
    $check_query = ['standard-186', 'upgrade-186', 'standard-184', 'upgrade-184'];
    
    $value = "standard";
    
    $range_array = array_filter($check_query, function($a) use($value){return (stripos($a, $value)!==false);});
    print_r($range_array);
    

    Output

    Array ( [0] => standard-186 [2] => standard-184 ) 
    

    For $spec_array do the same thing with a different value for $value.

    For PHP 8 you can use str_contains() instead of stripos():

    $res = array_filter($check_query, function($a) use($value){return str_contains($a, $value);});
    print_r($res);