PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] Switch case with multiple values from a checkbox field in ACF

 March 03, 2022     advanced-custom-fields, php, wordpress     No comments   

Issue

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!


Solution

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";
}
?>


Answered By - Growdzen
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing