1

I have since a few years back always wanted to make my PHP snippet even more useful to also use some kind of an IF statement. But I find it too complicated and so today I pushed me to finally ask for help.

So I need help with some coding do hide the text surrounding the variable if data is empty, but this code has some twist in it which I cannot solve. I have tried to make my snippet as clean as possible so hopefully it can still stay clean.

Please bear with me as my knowledge of PHP is very limited.

This code is part of a javascript to output given information.

{
title: "This is it",
file: "thisisit.mp4",
image: "happy.jpg",
description: "some text right here",
},

I have managed to wrap this part of javascript successfully inside PHP so I can use variables instead and have the information stored elsewhere externally.

echo '
{
title: "'.$data[2].' - '.$data[3].' ('.$data[0].') <img src=\"'.$data[10].'\"/>",
file: "'.$data[6].'",
image: "'.$data[9].'",
description: "'.$data[4].' <br><a href='.$data[8].'>Read more</a> ",
},
';

The above works as it should. If any variable is populated then it will display as it is and if empty then it will not output anything. But now I would like to have a template text or html around a variable to only display when there is data in the variable.

Take data[8] as an example. The data will only contain an URL to read more. Fine as long as there is an URL, but if no URL is given then it will only display a read more link with no URL. So if the data is empty then I would like to not display any text or links related to that data variable.

I have tried using IF statement but I dunno if it is the right way to go or I just do not know how to implement it correctly. What ever I do it will just end up in error.

Trial and error like this, still inside same echo

    echo '
    {
    title: "'.$data[2].' - '.$data[3].' ('.$data[0].') <img class=\"jwTitleIcon\" src=\"'.$data[10].'\"/>",
    file: "'.$data[6].'",
    image: "'.$data[9].'",
    description: "'.$data[4].'  '.if($data[8]) else{.'<br><a href='.$data[8].'</a>} ",
 },
 ';

Or trial and error like this, separating to another echo

echo '
{
title: "'.$data[2].' - '.$data[3].' ('.$data[0].') <img class=\"jwTitleIcon\" src=\"'.$data[10].'\"/>",
file: "'.$data[6].'",
image: "'.$data[9].'",
description: "'.$data[4].' ';
 if(empty($data[8]) else { echo ' <br><a href='.$data[8].'>Read more</a> } ",
},
';

Or this (found it at someone else's question) which gives no error but somehow the code is breaking something as html output is blank. Could be messing up the javascript as it is very sensitive

echo '
{
title: "'.$data[2].' - '.$data[3].' ('.$data[0].') <img class=\"jwTitleIcon\" src=\"'.$data[10].'\"/>",
file: "'.$data[6].'",
image: "'.$data[9].'",
description: "'.$data[4].' ';
echo !empty($data[8]) ? '<br><a href='.$data[8].'>Habba hej</a> ':' ",
},
';

Help appreciated. Thank you

1
  • 5
    Don't create JSON by hand like this, use json_encode(). Commented May 23, 2018 at 23:09

3 Answers 3

2

It's best to use json_encode() to convert a PHP value to a Javascript literal, rather than doing it with your own echo statements.

Within this you can use a tertiary operator.

$data2 = array(
    'title' => "$data[2] - $data[3] ($data[0]) <img class='jwTitleIcon' src='$data[10]'>",
    'file' => data[6],
    'image' => $data[9],
    'description' => $data[4] . (!empty($data[8]) ? "<br><a href='$data[8]'>Habba hej</a>" : "")
);
echo json_encode($data2) . ",";
Sign up to request clarification or add additional context in comments.

8 Comments

This answer is correct; don't use echo to produce serialization of objects, the OP is over-engineering.
Hi Barmar. Thank you for your comment. In this case the brackets is essential for the javascript to work. I get errors when trying to add the brackets into your example.
Barmar - Allthough you did help me with the !empty line of code! This actually did the trick using with echo. Perhaps not the best coding of not using json encode, but it works beautifully
What error do you get? json_encode() should include the brackets.
Just noticed that I had the wrong kind of quotes in class='jwTitleIcon', that would have caused a syntax error. It should work now.
|
0

As stated by Barmar, it will be easier for you to use json_encode.

This function takes an array as an argument and outputs the corresponding json.

So basically, what you need to do is create an array with the keys being your keys in the object.

I will do an example with your example (the description) and let you adapt for the rest.

$output = []; // We start with an empty array

// Let's consider that there is a description
$output['description'] = $data[4];

if(!empty($data[8])) { // If there is a link at $data[8], append it to the description
    $output['description'] .= '<br><a href='; // append the html
    $output['description'] .= $data[8]; // append the link
    $output['description'] .= '>Read more</a>'; // append the end of the html


    // One line equivalent :
    // $output['description'] .= '<br><a href=' . $data[8] . '>Read more</a>';
}

// Then you echo the json_encoded output
echo json_encode($output);

Another option is to use if-else statement like that :

$output = []; // We start with an empty array


// Let's consider that there is a description
if(!empty($data[8])) { // If there is a link at $data[8], set the description with a link
    $output['description'] = $data[4] . '<br><a href=' . $data[8] . '>Read more</a>';
} else { // Else = there is no link at $data[8]
    $output['description'] = $data[4];
}

// Then you echo the json_encoded output
echo json_encode($output);

The last option would be to use tertiary conditions which are basically a condition that "gives a value". Even though I believe this is not the best option in this case as I believe the instruction becomes quite long/harder to read :

$output = []; // We start with an empty array


// Let's consider that there is a description
$output['description'] = $data[4] . (!empty($data[8]) ? ('<br><a href=' . $data[8] . '>Read more</a>') : ''); // We add the link if there is a link at $data[8]

// Then you echo the json_encoded output
echo json_encode($output);

I have just seen that there is a "," at the end of your snippet. I believe you should therefore use an array of arrays and use json_encode on it. For example:

function snippet(&$json, $data) // The reason to put &$sjon and not $json is because we need to have a parameter passed by reference
{
    // HERE PLACE THE CODE OF YOUR SNIPPET
    $output = [];

    /* ... add the pieces of information into the output */

    $json[] = $output; // We add the $output to our array
}

$datas = [/*... array of $data*/];

$json = []; // Create the empty array
foreach ($datas as $data) {
    snippet($json, $data); // Call the snippet
}
echo json_encode($json);

4 Comments

Hi Alex. Yes the coma is essential for the code to work, without it the output will be blank. The brackets are also essential and without it the code is useless. Does this mean I cannot use your examples?
If you want a comma after each snippet, you can use the examples and add the coma here echo json_encode($output) . ',';. If you want the comma to be after each snippet except the last one, you can adapt the last example I gave to do exactly that. You just have to copy paste the code from one of the first 3 examples where I put /* ... add the pieces of information into the output */
Hi Alex. Thanks for still trying to aid me. Although I am still confused. Both the brackets and the comma are essential. I have put up an answer as you can se june 5 at 9:53 where I have commented which bracket is essential. The code which is echoed in my answer is also important that it looks exactly like that in the output html source code. Otherwise it breaks the javascript.
No problem, so basically, what you are echoing in javascript is an array of objects, am I correct (i.e. [{...}, {...}, {...}]) ?
0

Barmar helped me with one line of code!

. (!empty($data[8]) ? "<br><a href='$data[8]'>Habba hej</a>" : "")

This actually did the trick using with echo. Perhaps not the best coding of not using json encode which everyone recomended, but it works beautifully now as seen below.

Working

echo '
{ // <- Essential. Starting bracket 
title: "'.$data[2].' - '.$data[3].' ('.$data[0].') <img class=\"jwTitleIcon\" src=\"'.$data[10].'\"/>",
file: "'.$data[6].'",
image: "'.$data[9].'",
description: "'.$data[4] . (!empty($data[8]) ? '<br><a target=\"_blank\" href=\"'.$data[8].'\">Habba hej</a>' : ""). '",
}, // <- Essential. Ending bracket
';

If the code could be as simple as the above but instead b benefitting json encode then I can gladly make the changes. Just remember that the brackets and the comma }, are essential.

1 Comment

I´m sorry if I left out the one most important requirement. The javascript which I have output as echo is really important that it stays exactly the same in the html source code. Otherwise it will break the javascript. The PHP snippet is actually inside a javascript code because I needed the data in the output to be as variables. Sorry for the confusion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.