1

I am using a function in a separate file, that gets should return me an array containing the enum values of a field:

<?php 
function getEnumValues($table, $field) {
$enum_array = array();
$query = "SHOW COLUMNS FROM '{$table}' WHERE Field = '{$field}'";
$result = mysqli_query($query);
$row = mysqli_fetch_row($result);
preg_match_all('/\'(.*?)\'/', $row[1], $enum_array);
return $enum_array;
}
?>

and in the main file, I do this:

<?php
require 'common.php';
for ($i=0; $i <= 5; $i++) {
                getEnumValues(property, value_type);
                echo "<input type='radio' name='tipo_valor' value='$enum_array[$i]' required>" . '  ' .$enum_array[$i] . '<br>';
            }
?>

The problem is that the function returns nothing.

So is the function ok for what I need? And can I use a variable returned in another file, as a local variable?

Thanks for your time, and suggestions!

Wilhelm Sorban
  • 1,012
  • 1
  • 17
  • 37

1 Answers1

2

The function is returning a value; you're just not capturing it. The $enum_array in your function body only lives in the scope of that function. You need to put the return value of the function in a variable in scope. In your main file:

<?php
require 'common.php';
for ($i=0; $i <= 5; $i++) {
            $enum_array = getEnumValues(property, value_type);
            echo "<input type='radio' name='tipo_valor' value='$enum_array[$i]' required>" . '  ' .$enum_array[$i] . '<br>';
        }
?>
Rikki Gibson
  • 4,136
  • 23
  • 34
  • 1
    If property and value_type are unchanging parameters within the loop, then it would be more efficient to move the function call above the for loop, rather than call it every time the loop iterates. There's no point re-running the function if $enum_array is unchanging during the loop. – Martyn Shutt Dec 06 '14 at 21:29