0

In my file, I wrote the following code:

if ( is_array( $form_data['list'][95] ) ) {
    $i = 1;
    foreach ( $form_data['list'][95] as $row ) {
          /* Uses the column names as array keys */
          $name[$i] = $row['Name'];
          $phonetic[$i] = $row['Phonetic Spelling'];
          if ($phonetic[$i] == ''){$spelling[$i] = '';} else {$spelling[$i] = '('.$phonetic[$i].')';}
          $order[$i] = $row['Order'];
          $full_row[$i] = $order[$i].' - '.$name[$i].' '.$spelling[$i];
          $i++;
    }

rsort($full_row);
    foreach ($full_row as $key => $val) {
    echo "$val<br />";
    }
}

This works fine. It outputs the list that I would expect. However, if I try to output it as a function, nothing happens.

function OrderFormatIntros(){
if ( is_array( $form_data['list'][95] ) ) {
    $i = 1;
    foreach ( $form_data['list'][95] as $row ) {
          /* Uses the column names as array keys */
          $name[$i] = $row['Name'];
          $phonetic[$i] = $row['Phonetic Spelling'];
          if ($phonetic[$i] == ''){$spelling[$i] = '';} else {$spelling[$i] = '('.$phonetic[$i].')';}
          $order[$i] = $row['Order'];
          $full_row[$i] = $order[$i].' - '.$name[$i].' '.$spelling[$i];
          $i++;
    }

rsort($full_row);
    foreach ($full_row as $key => $val) {
    echo "$val<br />";
    }
  }
}
OrderFormatIntros();

Do I need to provide more explanation? Or is there a clear reason why the code won't output when called as a function?

osakagreg
  • 537
  • 4
  • 19
  • 4
    `$form_data` doesn't exist in the function's scope. Have a read of [this question](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and). – Jonnix Oct 25 '16 at 21:25

1 Answers1

2

The code inside the OrderFormatIntros function is not privy to the contents of the $form_data variable; You must pass it into the function, for example:

<?php
function OrderFormatIntros($form_data){
    if ( is_array( $form_data['list'][95] ) ) {
    $i = 1;

    foreach ( $form_data['list'][95] as $row ) {
    /* Uses the column names as array keys */
        $name[$i] = $row['Name'];
        $phonetic[$i] = $row['Phonetic Spelling'];

        if ($phonetic[$i] == ''){$spelling[$i] = '';} else {$spelling[$i] = '('.$phonetic[$i].')';}
            $order[$i] = $row['Order'];
            $full_row[$i] = $order[$i].' - '.$name[$i].' '.$spelling[$i];
            $i++;
        }

        rsort($full_row);

        foreach ($full_row as $key => $val) {
            echo "$val<br />";
        }
    }
}

OrderFormatIntros($form_data);
Drefetr
  • 412
  • 2
  • 7