Page 1 of 1

Logic

Posted: Tue Oct 05, 2010 11:57 am
by steadythecourse
Hi
I found this piece of code and I don't understand how the function is working, particularly the use of unset. It seems to me the code is destroying an increment statement. I'm very new to php, so please be kind. An explanation or even another way of achieving the same functionality in which the logic is more understandable (if that's possible) would be great.

Thanks,
Steadythecourse

Code: Select all


define("NUM_0", 0);
define("NUM_1", 1);
define("NUM_2", 2);
define("NUM_3", 3);
define("NUM_4", 4);

function function_1($position) {
  static $positions = array(NUM_0,
 NUM_1,
 NUM_2,
 NUM_3,
 NUM_4,),
  $index = 0;
  if (isset($positions[$index])) {
    while ($position >= $index) {
      $current_position = $positions[$index];
      unset($positions[$index++]);
      function_2($current_position);
    }
  }
}

function function_2($position) {

  switch ($position) {
    case 0:
      echo '$position equals 0 <br />';
      break;
    case 1:
      echo '$position equals 1 <br />';
      break;
    case 2:
      echo '$position equals 2 <br />';
      break;
    case 3:
      echo '$position equals 3 <br />';
      break;
    case 4:
      echo '$position equals 4 <br />';
      break;
  }
}

function_1(NUM_4);

[b]
output:

$position equals 0
$position equals 1
$position equals 2
$position equals 3
$position equals 4
[/b]


Re: Logic

Posted: Tue Oct 05, 2010 12:04 pm
by John Cartwright
1. Start at the first index
2. Check if the current index exists in our position array
3. Keep looping while the variable $position is less or equals to variable $index
4. Assign variable current position to the positions array current index.
5. Unset the next position array element from our current index.
6. Call function_2 with variable $current_position

What the purpose of this function is, I don't know. I hope this helps some.