$clean_matrix = array(); for ($i = 0; $i < count($matrix); $i++) { for ($j = 0; $j < count($matrix[$i]); $j++) { $clean_matrix[$i][$j] = clone $matrix[$i][$j]; } } return $clean_matrix; } // If a solution found add it to the solution array private function addSolution($s) { array_push($this->solution, $s); } // getSolutions public function getSolution() { return $this->solution; } } // And fire the application $matrixObj = new matrix(); $matrixObj->loopMatrix($matrix, false); $solutions = $matrixObj->getSolution(); echo "Problem to solve: How many combinations are there which leads to a sum of 10? From every field you can go to a neighboring field: top, down, left, right and diagonal is allowed. <br />"; $matrixObj->printMatrix($matrix); echo "<br />There are " . count($solutions) . " combinations which leads to a sum of 10.<br /><br />Solutions:<br />"; for ($i = 0; $i < count($solutions); $i++) { $clean_matrix = $matrixObj->cloneMatrix($matrix); echo '<br />' . ($i + 1) . '.'; $matrixObj->printMatrix($clean_matrix, $solutions[$i]); }