0

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

User301276
  • 55
  • 1
  • 8
  • What you're looking for is a variable variable. See https://stackoverflow.com/questions/25593055/variable-variables-in-php-what-is-their-purpose and https://stackoverflow.com/questions/3523670/whats-an-actual-use-of-variable-variables – aynber Sep 23 '21 at 18:23
  • 1
    Or use an array and `array_filter()` (with some minor warnings about what filtering actually removes). – Nigel Ren Sep 23 '21 at 18:26
  • Better off using an array `$field[1]` then you can access `$field[$a]` . – AbraCadaver Sep 23 '21 at 18:33

2 Answers2

1

Replace the line $fieldOutput = '$field_' . $a; with $fieldOutput = ${"field_$a"};. See the PHP documentation for variable variables.

George Sun
  • 968
  • 8
  • 21
1

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

    }

}

?>
Engr Talha
  • 386
  • 2
  • 6