0

I have to output a list of multiple values. These values are not part of an array. I am doing it like this:

$value_1 = get_field('value_1');
$value_2 = get_field('value_2');
$value_3 = some_other_function('value_3');
$value_4 = another_function('value_4', 'one_more_param');

echo '<ul>';

if ($value_1) :
  echo '<li>' . $value_1 . '</li>';
endif;

if ($value_2) :
  echo '<li>' . $value_3 . '</li>';
endif;

if ($value_3) :
  echo '<li>' . $value_3 . '</li>';
endif;

if ($value_4) :
  echo '<li>' . $value_4 . '</li>';
endif;

echo '</ul>';

I have about 30 values. Is there a quicker, cleaner way to output this?

2
  • 3
    Put the values in and array and loop through them. Commented Jul 26, 2019 at 14:01
  • security improvement : htmlentities($value_X) instead of just $value_X when you output data in HTML Commented Jul 26, 2019 at 14:06

2 Answers 2

2

Collect your values to array and iterate over this array:

$values = [
    get_field('value_1'),
    get_field('value_2'),
    some_other_function('value_3'),
    another_function('value_4', 'one_more_param'),
];
echo '<ul>';
foreach ($values as $value) {
    if ($value) {
        echo '<li>' . $value . '</li>';
    }
}
echo '</ul>';
Sign up to request clarification or add additional context in comments.

2 Comments

Ha! I didn't see the if() in the loop. How did I miss that?
That is brilliant! Works perfectly.
2

Create a function to check if it needs display the item, then pass the value each time...

function displayListItem( $value ) {
    if ( $value )   {
        echo '<li>'.$value.'</li>';
    }
}
echo '<ul>';
displayListItem(get_field('value_1'));
displayListItem(get_field('value_2'));
displayListItem(some_other_function('value_3'));
displayListItem(another_function('value_4', 'one_more_param'));
echo '</ul>';

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.