Could use some insight with stepping through this code

Can someone please take the time to step me through this simple code?

I can understand most of it, but the $data used as an array is throwing me. It doesn’t appear to be assigned any values therefore the reset($data) doesn’t make sense to me.

Cheers for the input!

<?php function create_table($data) { echo '<table border=\'1\'>'; reset ($data); $value = current($data); while ($value) { echo '<tr><td>' . $value . '</td></tr>\n'; $value = next($data); } echo '</table>'; } $my_array = array('Line one.' ,'Line two.', 'Line three.'); create_table($my_array); ?>

Reset is not used in the context you are thinking of. The reset function rewinds the array’s internal pointer to the first array element. So every time the function is called the reset function ensures that $data starts from the very beginning. I hope It makes sense now. 8)

Thanks for clarifying the reset function.

But I’m still unclear on the information in the array for $data. I see that it’s being used in the while loop but what information is being passed to $data? (the echo


The $data (array) variable contains following information:

'Line one.' ,'Line two.', 'Line three.'

because it is stored in the $my_array variable and then used as an argument for create_table function.

[php]$my_array = array(‘Line one.’ ,‘Line two.’, ‘Line three.’);

While loop starts from the beginning, and on each iteration moves to the next element until it reaches the last element (entry) in the array. When there is no entry left the loop exists.

Thanks for breaking it down, I think what’s throwing me is I don’t see where $data is connected to $my_array.

I was expecting to see $data = $my_array for example, if that makes sense.

In this case both $data and $my_array are connected to each other.

Functions are designed in a way that they can’t access other variables outside of the function. Similarly you can’t access a variable directly if it is inside a function. As a remedy Parameters comes into play.

[php]function create_table($data)[/php]

This is called a function definition and $data variable in this case is a Parameter for the create_table function. This parameter acts like a bridge or door for the variables that are outside of the function. This parameter is helping the information to get into the function.

Basically we have two variable (arrays).

  1. The $my_array variable can’t get directly into the function.
  2. So it passes the information to another variable i.e. $data
  3. $data grabs the information then it do its processing.

I hope this makes sense now. 8)

Cheers mate, this is starting to make more sense. Thanks for the time to step through this.

You are welcome.

Sponsor our Newsletter | Privacy Policy | Terms of Service