phparraysgroupingprefix

How to separate a php array items by prefix


I want to separate a PHP array when they have a common prefix.

$data = ['status.1', 'status.2', 'status.3',
         'country.244', 'country.24', 'country.845',
         'pm.4', 'pm.9', 'pm.6'];

I want each of them in separate variables like $status, $countries, $pms which will contain:

$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]

My Current code is taking 1.5 seconds to group them:

$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
    if(strpos($item, 'status.') !== false){
        $statuses[]= substr($item,7);
    }

    if(strpos($item, 'country.') !== false){
        $countries[]= substr($item,8);
    }

    if(strpos($item, 'pm.') !== false){
        $pms[]= substr($item,3);
    }
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);

I want to know if is there any faster way to do this


Solution

  • This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.

    For separating the value you can use: extract

    Consider the following code:

    $data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
    
    $res = array();
    foreach($data as $elem) {
        list($key,$val) = explode(".", $elem, 2);
        $res[$key][] = $val;
    
    }
    extract($res); // this will separate to var with the prefix name
    
    echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
    

    This snippet took less the 0.001 second...

    Thanks @mickmackusa for the simplification