4

Can someone tell me what the difference between these two loops / code snippets are?

I am getting the same output, but a text book is indicating there is a difference with the outer and inner loop? Any clarification would be helpful. I don't think I am understanding the list with each function.

Array definition:

$newArray  = array(array('CODE' => 'TIR', 'Description' =>'TIRES', 'Price' => 100),
                   array('CODE' => 'OIL', 'Description' => 'Oil', 'Price' =>10),
                   array('CODE' => 'SPK', 'Description' => 'Spark Plug', 'Price' =>40)
             );

Code snippet 1:

for ($row = 0; $row < 3; $row ++)
{           
    echo ' |'.$newArray[$row]['CODE'].'| '.$newArray[$row]['Description']. '| '.$newArray[$row]['Price'];
    echo  '<br />';
    echo  '<br />';      
}

Code snippet 2:

for ($row =0; $row <3; $row ++)
{
    while (list($key, $value) = each ($newArray[$row]))
    {
        echo "|$value";
    }
    echo  '<br />';
    echo  '<br />';
}
1
  • 4
    Well, once you hardcode the second dimension keys and in the second one you use a while loop to loop through all elements of each subArray. Just add another value to each subArray and you will see it, something like: "another element" => "Will only be shown by the second code snippet" Commented Apr 12, 2016 at 7:21

1 Answer 1

1

Yes, there's a difference if you look at it from algorithm point of view.

The first one has the time complexity of O(n) and the second one O(n2).

So, the first one is more efficient.

Sign up to request clarification or add additional context in comments.

2 Comments

The two code snippets do net the same ting, so you can't really compare them.
Well you are assuming that the second dimension is hardcoded, I am assuming both array length and dimension to be variable.

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.