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
json_encode().