0

I need to retain rows in my multidimensional array where multiole conditions must be met.

$positions = [
    ['64', '64', 'home.png', 'www.sdsd.vf'],
    ['128', '640', 'icon-building64.png', 'www.sdsd232.vf']
];

for ($i = 0; $i < 700; $i += 64) {
    for($j = 0; $j < 1100; $j += 64) {
        $out = array_filter(
            $positions, 
            function($position) {
                  return ($position[0] == $j AND $position[1] == $i);
             });    
        $out = array_merge(array(), $out);
    }
}

I tried this but I get errors:

$out = array_filter(
    $positions,
    function($position, $i, $j) {
        return ($position[0] == $j AND $position[1] == $i);
    }
);  
1
  • You are aware that both your for loops got no ending } (and one doesn't have {) Commented Feb 28, 2011 at 9:52

2 Answers 2

1

You can consolidate all conditions inside of a solitary array_filter() call.

function filterPositions($value) {
    return $value[0] < 1100
           && $value[1] < 700
           && ($value[0] % 64 == 0)
           && ($value[1] % 64 == 0);
}
$out = array_filter($positions, 'filterPositions');

Or a more concise and modern version with arrow function syntax.

var_export(
    array_filter(
        $positions,
        fn($row) =>
            $row[0] < 1100
            && $row[1] < 700
            && ($row[0] % 64 == 0)
            && ($row[1] % 64 == 0)
    )
);
Sign up to request clarification or add additional context in comments.

Comments

0

The best way to do this, is passing the $i and $j to your anonymous function

$out = array_filter($positions, function($position) use ($i, $j) {
                  return ($position[0] == $j AND $position[1] == $i);
    });

This way you will be avoiding hardcoding values in function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.