\$temp = array(1 => array(), 2 => array(), 3 => array(), 4 => array()); \$temp_out = array(1 => array(), 2 => array(), 3 => array(), 4 => array()); \$num = array(1 => 0, 2 => 0, 3 => 0, 4 => 0); \$x = 0; while (\$x < 4) { \$y = 0; while (\$y < 4) { \$var = \$numbers[\$x + 4*\$y]; if (\$var != 0) { \$temp[\$x + 1][] = \$var; \$num[\$x + 1]++; } \$y++; } if (\$num[\$x + 1] > 0) { \$b1 = \$temp[\$x + 1][0]; if (\$num[\$x + 1] > 1) { \$b2 = \$temp[\$x + 1][1]; if (\$num[\$x + 1] > 2) { \$b3 = \$temp[\$x + 1][2]; if (\$num[\$x + 1] > 3) \$b4 = \$temp[\$x + 1][3]; else \$b4 = 0; } else \$b3 = \$b4 = 0; } else \$b2 = \$b3 = \$b4 = 0; } else \$b1 = \$b2 = \$b3 = \$b4 = 0; if (\$b1 == \$b2) { \$b1 = \$b1 + \$b2; if (\$b3 == \$b4) { \$b2 = \$b3 + \$b4; \$b3 = 0; } else { \$b2 = \$b3; \$b3 = \$b4; } \$b4 = 0; } elseif (\$b2 == \$b3) { \$b2 = \$b2 + \$b3; \$b3 = \$b4; \$b4 = 0; } elseif (\$b3 == \$b4) { \$b3 = \$b3 + \$b4; \$b4 = 0; } \$temp_out[\$x + 1][0] = \$b1; \$temp_out[\$x + 1][1] = \$b2; \$temp_out[\$x + 1][2] = \$b3; \$temp_out[\$x + 1][3] = \$b4; \$x++; }