- substr: documentation ( source)
- var_dump: documentation ( source)
<?php
$postcodes = ['SO30 0NG', 'SO30 OTD', 'SO31 1TG', 'RG51 5HG', 'RG51 7GH'];
$result= array();
Foreach ($postcodes as $postcode){
$short =Substr($postcode,0,4);
If(!isset($result[$short])) $result[$short]=[];
$result[$short][]= $short;
}
Var_dump($result);