2

Can someone explain the logic behind this for loop... I just don't get it on how it goes into the next element, that $from[$i], what is it doing?

$start = 2;

$path = array();
for (; $i != $start; $i = $from[$i])
         $path[] = $i;
0

2 Answers 2

3

It's not very clearly written. I assume $i and $start are previously initialized.

Basically, there is no for loop initialization. It continues until $i equals $start. In the body, $i is appended to the $path array. Before going to the next iteration, $i is set to the value of the $i key in $from.

So if the array looked like:

$from = array('foo'=>'bar', 'bar'=>'baz', 'baz'=>'goo');

and $i are $start are 'foo' and 'goo' respectively, $path will end up:

array('foo', 'bar', 'baz')

If $start is unreachable, it will loop forever.

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

Comments

2

I'm guessing $from is an array that maps what the next $i should be based on a given $i.

So for each iteration, $i is assigned the value in $from at index $i.

(eg. if $i is 5 and $from[5] is 4, then the next value for $i is 4)

And it stops when it reaches the value $start.

Would need to know a bit more about what's in $from to help you further.

Comments

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.