Search code examples
phparraysforeach

Must a foreach loop be used if my 2d array only has one row?


I am still very new to PHP and from all the examples that are around they all seem to use foreach statements.

e.g.

foreach ($variable as $row)

However I don't think I should be using this all the time, for example variables or objects I have an which only has one row or instance in an array.

I know its advantageous to use them for multiple rows which could be missed if you used a for loop.

But do I really need to use it just to echo one variable thats in an array?

e.g. for example this variable $stats

array(3) {
    ["user_interventions"] => int(4)
    ["fastest_intervention"] => array(1) {
        [0] => object(stdClass)#22 (1) {
            ["duration"] => string(8) "02:10:00"
        }
    }
    ["slowest_intervention"] => array(1) {
        [0] => object(stdClass)#23 (1) {
            ["duration"] => string(8) "02:26:00"
        }
    }
} 

Solution

  • No, you do not need to use a foreach loop every time you need to access an array value. Your example could be used in the following manner...

    echo $stats['fastest_intervention']['0']->duration; // Outputs: 02:10:00
    

    Here's your variable dump with indentation (makes it easier to read).

    array(3) {
        ["user_interventions"]=> int(4)
        ["fastest_intervention"]=> array(1) {
            [0]=> object(stdClass)#22 (1) {
                ["duration"]=> string(8) "02:10:00"
            }
        }
        ["slowest_intervention"]=> array(1) {
            [0]=> object(stdClass)#23 (1) {
                ["duration"]=> string(8) "02:26:00"
            }
        }
    }