-1

I have multiple checkboxes, lets say;

<input type="checkbox" value='One' />
<input type="checkbox" value='Two' />
<input type="checkbox" value='Three' />

My php looks like;

echo implode(', ', get_field('checkboxes'));

When I check all the boxes my output looks like;

One, Two, Three

But, I am looking for a way my output looks like;

One, Two & Three

And when I check only two boxes the output will be;

One & Two

Can't find this anywhere, please help!

Cheers

2 Answers2

3

Supposing you have an array of values, you can use array_slice to pick only a certain part of an array to make the implode, and then complement with the last &. Here's a function of example:

function show_values($values) {
    $size = count($values);

    $text = implode(', ', array_slice($values, 0, -1));
    $text .= ($size > 1) ? ' & ' : '';
    $text .= $values[$size - 1];

    return $text;
}

echo show_values(array('One')) . "\n"; // One
echo show_values(array('One', 'Two')) . "\n"; // One & Two
echo show_values(array('One', 'Two', 'Three')) . "\n"; // One, Two & Three
Guilherme Sehn
  • 6,727
  • 18
  • 35
0

use the following code

$checkboxes = get_field('checkboxes');

$output = '';
$length = count($checkboxes);
for($i = 0 ; $i < $length; $i++) {
    if($i < $length - 1) {
        $output .= $checkboxes[$i] . ', '; 
        continue;
    }

    $output .= '& ' . $checkboxes[$i];
}

echo $output;
Ulrich Horus
  • 352
  • 3
  • 9