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
CodePudding user response:
Replace the line $fieldOutput = '$field_' . $a;
with $fieldOutput = ${"field_$a"};
. See the PHP documentation for variable variables.
CodePudding user response:
Explain: Solution: First create of array of all variables. then iterate that array.
<?php
$field_1 = "john";
$field_2 = "";
$field_3 = "jack";
$data=array($field_1,$field_2,$field_3);
for($a = 0; $a < count($data); $a )
{
if($data[$a]){
echo '<br>'.$data[$a];
}
}
?>