Reputation: 4742
Suppose I have 2d array, where only some rows actually have some values in the columns, whereas other rows don't have anything.
For example: only rows 5 and 9 have some data, other rows are empty. Number of columns is fixed - 6
I have not declared any size for the 2D array.
I want to find all fields whose value is 10.
for ($t1=0; $t1 < count($array); $t1++) {
for ($t2=0; $t2 < 6; $t2++) {
if($array[$t1][$t2] == 10) {
// do something
}
}
}
Now this code won't work because count($array) will be 2, so it will never iterate for rows 5 and 9.
I also need to get the index at which I found a match.
How can I write code to make it work in this case?
Upvotes: 0
Views: 43
Reputation: 377
You can effectively use foreach
in this case:
foreach($array as $s => $arrayElement) {
for($t=0; $t<6; $t++) if ($arrayElement[$t] == 10) {
// do something - $s is the row index, $t is the column index
}
}
Upvotes: 1
Reputation: 147
I think , you have a problem in defining array. May be , you can use this script.
<?php
$cars = array(
array(
"Volvo",
22,
18
),
array(
"BMW",
15,
13
),
array(
"Saab",
5,
2
),
array(
"Land Rover",
17,
15
),
array(
"Mercedes",
22,
19
)
);
$length = count($cars);
for ($i = 0; $i < $length; $i++) {
for ($j = 0; $j < 3; $j++) {
echo $cars[$i][$j] . "</br>";
}
}
?>
I hope , it will solve your problem.
Upvotes: 0