So I have two-dimensional arrays of N * M like below,
$arys = [
[0] => [0, 0 , 0 , 0],
[1] => [0, 1 , 0 , 0],
[2] => [0, 0 , 1 , 0],
[3] => [0, 0 , 0 , 0],
and need to detect ‘1’ and if there’s ‘1’, i need to get values vertically and horizontally, and change them to ‘1’, which is like below,
$arys = [
[0] => [0, 1 , 1 , 0],
[1] => [1, 1 , 1 , 1],
[2] => [1, 1 , 1, 1],
[3] => [0, 1 , 1 , 0],
I kind found out that I need to use ‘for’ inside ‘for’, but can’t do that.
Guess this is a very basic PHP code but appreciate if someone would help with it.
2
Answers
The basics of it is:
But the pitfall you’re going to run into is if you start changing zeroes to ones in the array you’re currently reading you’re going to wind with incorrect output. Write your output to a new 2D array.
2 foreach loops are used to iterate over all elements of $arr. If there is a 1 in the row or in the column (via array_column), the new value is also set to 1, otherwise 0.
Demo : https://3v4l.org/XYS0a