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

3
  • What you're looking for is a variable variable. See stackoverflow.com/questions/25593055/… and stackoverflow.com/questions/3523670/… Commented Sep 23, 2021 at 18:23
  • 1
    Or use an array and array_filter() (with some minor warnings about what filtering actually removes). Commented Sep 23, 2021 at 18:26
  • Better off using an array $field[1] then you can access $field[$a] . Commented Sep 23, 2021 at 18:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

    }

}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.