Alok
Alok

Reputation: 8998

Implement inline ternary operator in embedded HTML in PHP

I am a learner in PHP, and I have a code in which I am implementing HTML5 code. What I am trying to do is to embed the inline ternary operator in my placeholder.

I have followed this link, but none of them are having same problem statement:

  1. Putting inline style using ternary operator php
  2. Inline PHP/HTML Ternary If

My Code:

echo "<input type='text' class='form-control' value='".$value."' placeholder='HERE I WANT TO OPERATE'>";

Tried: I have tried this in my code, but I am getting errors

echo "<input type='text' class='form-control' value='".$value."' placeholder='"empty($value) ? 'Some Text' : 'Enter Data';"'>";

I know how to do the ternary operation outside the echo code in PHP, but I am looking for this way.

Upvotes: 1

Views: 986

Answers (3)

coderman401
coderman401

Reputation: 582

you can try this... hope it will help

echo "<input type=\"text\" class=\"form-control\" value=\"$value\" placeholder=" . $value == "" ? "Some Text" : "Enter Data";">";

Upvotes: 2

wxker
wxker

Reputation: 1896

The ternary operation will return a string. As such, it has to be concatenated to the rest of the string.

echo "<input type='text' class='form-control' value='".$value."' placeholder='". (empty($value) ? 'Some Text' : 'Enter Data') ."'>";

Upvotes: 1

Aksen P
Aksen P

Reputation: 4599

Separate part of string with condition with help of ():

echo "<input type='text' class='form-control' 
value='".$value."' 
placeholder='".(empty($value) ? "Some Text" : "Enter Data")."'>";

Note: you're using empty() function on $value, if it has some text then it will go into false case -> "Enter Data". Use !empty() instead.:

(!empty($value) ? "Some Text" : "Enter Data")

Upvotes: 2

Related Questions