2

Here i have the variable $json concatenated with possible three conditions.

According the below conditions $first , $second and $third, the output should get concatenate with pipe. So that the output should be either three given below

Expected


first
or 
first | second
or 
first | second | third

Here is my Code simplified :

<?php
$json = "";
$first = "1";
$second = "1";
$third = "1";
$pipe = "|";
        if ($first == 1)
        {        
        $json .= "first";
        }
        $json .= $pipe;
        if ($second == 1)
        {        
        $json .= "second";
        }
        $json .= $pipe;
        if ($third == 1)
        {
        $json .= "third";
        }    
    echo $json;
?>

How can i make the $pipe variable to get my output expected for the variable $json

Note : As i use some complex flexi grid , implode still makes little complex

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63

4 Answers4

3

Try this:

$json = "";
$first = "1";
$second = "1";
$third = "1";
$pipe = "|";
$data = array();
if ($first == 1)  $data[] = "first";
if ($second == 1) $data[] = "second";
if ($third == 1)  $data[] = "third";
$json = implode($pipe, $data);
echo $json;

Or use some other way, like this for example.

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107
2

You can do this:

$array = array(
    'first'  => $first,
    'second' => $second,
    'third'  => $third
);

echo implode($pipe, array_keys(array_filter($array)));

array_filter removes any key/value pair whose value is falsely, array_keys returns an array of their keys, and implode joins the values using $pipe.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

The easiest solution for this is to always concatenate a pipe after a variable concatenation Then truncate the the final string by 1 character. If you're printing straight to stdout, remove this last pipe with a back-space, space combination.

phil
  • 561
  • 3
  • 10
0
$json;
$first = true;
$second = true;
$third = true;
$pipe = " | ";

if ($first === true) {
    $json .= "first";
}
if ($second === true) {
    $json .= $pipe . "second";
}
if ($third === true) {
    $json .= $pipe . "third";
}
echo $json;
MrGrigri
  • 304
  • 4
  • 15