Home > Net >  Switch case with multiple values from a checkbox field in ACF
Switch case with multiple values from a checkbox field in ACF

Time:02-16

I have a Advanced Custom Fields checkbox with 5 values. A user can check max two values. Now I want to display an image based on the input. I would like to use the switch case in PHP, but can't get it to work. I want some thing like this

if the value = A then show image a.jpg
if the value = B then show image b.jpg
if the value = C then show image c.jpg
if the value = D then show image d.jpg
if the value = E then show image e.jpg
if the value = A and B then show image a-b.jpg
if the value = B and C then show image b-c.jpg
if the value = B and D then show image b-d.jpg
etc..

I had something like:

<?php
$checkbox = get_field('my_checkbox');

switch($checkbox){

case "A":
        echo "<img src="a.jpg">";
        break;
case "B":
        echo "<img src="b.jpg">";
        break;
case ("A" && "B"):
        echo "<img src="a-b.jpg">";
        break;
case ("B" && "C"):
        echo "<img src="b-c.jpg">";
        break;
 // Default
    default:
        echo "No choice made yet";
        break;
}

But that doesn't work. Can someone get me on the right track? Thanks!

CodePudding user response:

A Switch Case structure basically fires at the first match. What you need to do is first recognize the cases in which there are a multitude of answers given rather than a single value. You can use the example below to expand on. Don't forget to set conditional logic on the ACF checkbox that prevents users from selecting more than 2 options (as it seems you don't have images consisting out of more than 2 values)

<?php
$checkbox = get_field('my_checkbox');
$checkbox = array( $checkbox ); 
if( $checkbox && in_array( array( 'A' , 'B' ), $checkbox) ) {
    $key = "a-b.jpg";
} elseif ( $options && in_array(array('a'), $checkbox) ) {
    $key = "a.jpg";
} elseif ($options && in_array(array('b'), $checkbox) ) {
    $key = "b.jpg";
}
?>
  • Related