Search code examples
phparraysalgorithmoptimizationexecution

Conditionally replace elements in PHP 2D array


Currently, i am using the following code to replace the elements of an array which are greater than the $value

for($i=0;$i<$row;$i++) {
            for($j=0;$j<$column;$j++) {
                if($solution[$i][$j] >= $value) {
                    $solution[$i][$j] = -1;
                }
            }
        }

Is there a better and faster way to do it? I have a complex algorithm to generate the puzzle and i am trying to optimize the execution time. This code is a part of the algorithm.

EDIT:

These are the execution times that i get by trying different solutions:

For loops:

4.1007995605469E-5

Answer by mark:

0.00057792663574219

Foreach loops:

2.9087066650391E-5

Solution

  • Try

    array_walk_recursive(
        $solution, 
        function(&$aVal, $key, $value) {
            $aVal = ($aVal >= $value) ? -1 : $aVal;
        },
        $value
    );
    

    but you'll need to benchmark