3v4l.org

run code in 300+ PHP versions simultaneously
<?php $category_input = array( 'cat_20', 'post-in-cat-20', 'post-in-cat-20', 'post-in-cat-20', 'cat_19', 'post-in-cat-19', 'post-in-cat-19', 'post-in-cat-19', 'post-in-cat-19', 'cat_2', 'post-in-cat-2', 'post-in-cat-2', 'post-in-cat-2' ); $out_arr = array(); foreach($category_input as $val){ $part = explode('_', $val); if(isset($part[0]) && $part[0] == 'cat'){ $out_arr[$val] = array(); $key = $val; }else{ $out_arr[$key][] = $val; } } print_r($out_arr);
Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
Array ( [cat_20] => Array ( [0] => post-in-cat-20 [1] => post-in-cat-20 [2] => post-in-cat-20 ) [cat_19] => Array ( [0] => post-in-cat-19 [1] => post-in-cat-19 [2] => post-in-cat-19 [3] => post-in-cat-19 ) [cat_2] => Array ( [0] => post-in-cat-2 [1] => post-in-cat-2 [2] => post-in-cat-2 ) )

preferences:
107.98 ms | 2102 KiB | 4 Q