Reputation: 944
The user gets several options which adds a different class into something that is read into PHP -
The below works, but it seems very inefficient and uses a lot of code. Is there a way I can cut this down?
<?php
if(get_sub_field('status') == "Upcoming"){
echo '<li class="upcoming">';
}
if(get_sub_field('status') == "Next"){
echo '<li class="next">';
}
if(get_sub_field('status') == "See what happened"){
echo '<li class="happened">';
}
?>
Upvotes: 2
Views: 89
Reputation: 14649
You could make a table that holds the available values for which you want. This way eliminates all of the if statements. Keep in mind thought that this is functionally equivalent to your code above.
$opt_vals = array(
"Upcoming",
"Next",
"See what happened"
);
$val_to_search = get_sub_field("status");
if(($key = array_search($val_to_search, $opt_vals)) !== FALSE) {
echo '<li class="' . strtolower($val_to_search) . '">';
}
Since array_search
returns the key with the corresponding value, $key
would hold the key, but as @Timur emphasized, a value at corresponding index 0, would evaluate to FALSE, 0, so in order to really check if it has the value we have to use the strict !==
operator because 0 == NULL
would evaluate to true.
Upvotes: 4
Reputation: 59701
The only way you could change it is this:
echo '<li class="' . get_sub_field('status') . '">';
Otherwise there is no way around this! You have to use if
and elseif
or you make a switch
statement
When you sill want to look if the value is valid you can make a array like a whitelist:
$valid = array(
"Upcoming",
"Next",
"See what happened"
);
And then you can check it like this:
if($value = array_search(get_sub_field("status"), $valid))
echo '<li class="' . strtolower($value) . '">';
else
echo '<li class="default">'; //if something fails
Upvotes: -1
Reputation: 317
you can do it with if...else if like this.
<?php
$status = get_sub_field('status');
if( $status == 'upcoming')
$class = 'upcoming';
else if( $status == 'Next' )
$class = 'next';
else if( $status == 'See what happened')
$class = 'happened';
?>
<li class="<?php echo $class; ?>"></li>
Upvotes: 0