What is the best way to rewrite this repeated if statement?

I think there is an easier way to write this code, but not sure which approach to take. Basically, I want to check if every variable exists, and if so, add the appropriate markup to the page.

Any suggestions would be great.

<?php $words = get_field('words'); $photography = get_field('photography'); $architect = get_field('architect'); ?> <div class="panel"> <?php if( $words ): ?> <div> <p><span>Words</span><span><?php echo $words;?></span></p> </div> <?php endif ;?> <?php if( $photography ): ?> <div> <p><span>Photography</span><span><?php echo $photography;?></span></p> </div> <?php endif; ?> <?php if( $architect ): ?> <div> <p><span>Architect</span><span><?php echo $architect;?></span></p> </div> <?php endif; ?> </div> 
+5
source share
4 answers

You can use array and loop -

 <?php $fields = array(); $fields['words'] = get_field('words'); $fields['photography'] = get_field('photography'); $fields['architect'] = get_field('architect'); ?> <div class="panel"> <?php foreach($fields as $key => $value): if($value) ?> <div> <p><span><?php echo ucwords($key);?></span><span><?php echo $value;?></span></p> </div> <?php endif; endforeach;?> </div> 
+5
source

Create an array of fields with the appropriate label if you want to have your own labels.

 <div class="panel"> <?php $fields = array ( 'words' => 'Words', 'photography' => 'Photography', 'architect' => 'Architect' ); foreach ( $fields as $field => $label ) { $value = get_field ( $field ); if (!empty($value)) { echo '<div> <p><span>' . $label . '</span><span>' . $value . '</span></p> </div>'; } } ?> </div> 
+5
source
 <?php $required_fields = array("words","photography","architect"); $data = array(); foreach($required_fields as $field) { $data[$field] = get_field($field); } ?> <div class="panel"> <?php foreach($data as $data_field=>$data_value): if($data_value) ?> <div> <p><span><?=$data_field?></span><span><?=$data_value?></span></p> </div> <?php endif; endforeach ;?> </div> 
+1
source

You can create such a function and then iterate over the received data to display your content

 <?php //define a function to fetch data in specific fields function fetch_data($keys=array()){ $data = array(); foreach($keys as $key){ $val = get_field($key); if(!empty($val)){ $data[$key] = $val; } } return $data; } //now you can easily add or change your fields $data = fetch_data(array('words','photography','architect')); ?> <div class="panel"> <?php foreach($data as $field){ if(isset($data[$field])){ $val = $data[$field]; ?> <div> <p><span><?php echo ucfirst($field); ?></span><span><?php echo $val; ?></span></p> </div> <?php } } ?> 
+1
source

All Articles