I made a table from your code:
col 4 3 2 1 0
row
4 5 5 5 5 5
3 5 4 4 4 4
2 5 4 3 3 3
1 5 4 3 2 2
0 5 4 3 2 1
There's a pattern here: the value of a cell is equal to its distance from 0,0 (see how like-numbers form 'squares' centered around the bottom-right corner).
Or:
cell = Max( x, y ) + 1
...kinda simple, eh?
Consider this as proof:
cell4,4 = Max( 4, 4 ) + 1 == 5
cell2,3 = Max( 2, 3 ) + 1 == 4
For your PHP, this is:
$d = max( $col_diff, $row_diff ) + 1;
It's that simple!
If your domain is limited to the range 4-0, then add a clamp:
$d = max( max( min( $col_diff, 4 ), 0 ), max( min( $row_diff, 4 ), 0 ) + 1;