In PHP I have 3 fields. I want to only output fields that have a value using a loop.
$field_1 = "john";
$field_2 = "";
$field_3 = "jack";
for($a = 1; $a <= 3; $a++)
{
$fieldOutput = '$field_' . $a;
if (!empty($fieldOutput)) {
echo $fieldOutput;
}
}
My desired output is: john jack
...but the code above outputs $field_1
. I'm looking to output the actual value of the field though.
...how please can I amend the for loop code to achieve that. Thanks
Replace the line $fieldOutput = '$field_' . $a;
with $fieldOutput = ${"field_$a"};
. See the PHP documentation for variable variables.