osakagreg osakagreg - 1 month ago 5
PHP Question

Why won't my code output when called as a PHP function?

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?

Answer

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);