0

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?

2 Answers 2

1

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
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I tried using foreach, but could not write correct code. Can you write the complete code for this case?
In the internals of foreach loop you use $arrayElement as the direct pointer to your row (and thus you don't have to use an iterator for it). You don't use $array in the internals. (The internal loop will thus be single-dimensional traditional for loop - or you can replace even it with foreach if you do not need column index.)
I also need to get the index at which I found a match. How do I get the index?
I updated the code example to cover your case. The row index is assigned to $s.
0

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.

1 Comment

It's about array with non-monotonic key values, so your example won't work as expected.

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.