aherlambang
aherlambang

Reputation: 14418

looping through php array

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;

Upvotes: 2

Views: 104

Answers (2)

Matthew Flaschen
Matthew Flaschen

Reputation: 285027

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.

Upvotes: 3

Ben
Ben

Reputation: 21249

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.

Upvotes: 2

Related Questions