Как оптимизировать php код?
Например так. Задать массив, описывающий подходящие индексы и соответствующие им размеры, искать подходящий индекс через array_search и заполнять нужные переменные:$img_width = '';
$img_height = '';
$grid_num = '';

$settings = array(
    array(
        'indexes'    => array(2, 4, 5, 11, 13, 14, 15, 16, 20, 21, 23, 24, 25, 27, 28, 31, 32, 35, 36, 38, 39, 41),
        'img_width'  => 100,
        'img_height' => 100,
        'grid_num'   => 1
    ),
    array(
        'indexes'    => array(1, 3, 7, 8, 9, 10, 12, 17, 19, 22, 26, 29, 30, 34, 37, 42),
        'img_width'  => 400,
        'img_height' => 500,
        'grid_num'   => 2
    ),
    array(
        'indexes'    => array(6, 18, 33, 40),
        'img_width'  => 430,
        'img_height' => 240,
        'grid_num'   => 3
    )
);

foreach ($settings as $setting) {
    if (array_search($count_block, $setting['indexes']) !== false) {
        $img_width  = $setting['img_width'];
        $img_height = $setting['img_height'];
        $grid_num   = $setting['grid_num'];
        break;
    }
}
Если числа не связаны никакой логикой, то хотя бы так :$numbArr["450_500"] = array(1,6,7,15,46,20);
$numbArr["100_100"] = array(5,20);
$numbArr["430_420"] = array(7,20);
if(in_array($count_block,$numbArr["450_500"])){
   $img_width = '400';
   $img_height = '500';
   $grid_num = '2';
}elseif(in_array($count_block,$numbArr["100_100"])){
   $img_width = '100';
$img_height = '100';
$grid_num = '1';
}elseif(in_array($count_block,$numbArr["430_420"])){
  $img_width = '430';
$img_height = '240';
$grid_num = '3';
}