CSS style if/else statement not responding - php

I am trying to have set the position of my li element according to the value of the variable that I will be displaying. For some reason this doesn't seem to be working. Does anyone see anything wrong with my code? Thanks
echo "<li class=\"compensation_post posts_values\" if($compensation == \"Free\") {style=\"left: 540px;\"}>$compensation</li>";

PHP can parse variables in a double-quoted string, but not conditions. So you're going to need to break this out in one of two ways:
Separated:
$style = '';
if ($compensation == "Free")
$style = " style=\"left:540px;\"";
echo "<li class=\"compensation_post posts_values\"$style>$compensation</li>";
Or in-line:
echo "<li class=\"compensation_post posts_values\" "
. ($compensation == "Free" ? "style=\"left:540px;" : "")
. ">$compensation</li>";
I suppose you can also go in and out of php code like:
?><li class=\"compensation_post posts_values\" <?= ($compensation == "Free" ? "style=\"left:540px;\"" : ""); ?>>$compensation</li>

You cannot use an if statement like that. Instead, you could use a shorthand if. Something like this should work:
echo "<li class=\"compensation_post posts_values\"" . (($compensation == 'Free') ? 'style=\"left: 540px;\" : '') . ">$compensation</li>";
Or, you could do like this:
if ($compensation == 'Free')
$style = 'style="left: 540px;"';
echo "<li class=\"compensation_post posts_values\" $style>$compensation</li>";

Related

PHP ternary operators error when concatenating string [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 3 years ago.
I'm essentially converting this php code into a string assigned to a var so I can return it's value within a function:
<?php if ($add_cta=='yes' ){?>
<a class="button" href="<?php echo strip_tags(trim($a_href)); ?>">
<?php echo strip_tags(trim($a_title)); ?>
</a>
<?php } ?>
I have converted the above into the following:
$html = '
($add_cta == "Yes" ? .
' < a class = "button" href = "'.strip_tags(trim($a_href)).
'" > '.strip_tags(trim($a_title)).
' < /a>'. : "")
';
return $html;
But getting unexpected '.' errors on the line ($add_cta == "Yes" ? .'
But that is required to concat the string and php, right? where am I going wrong
You have to correct the usage of your single quotes. Especially the first and the last single quotes are not necessary. PHP does not execute any code inside the single quotes. You can use double quotes, but this will only print variables and makes things more complicated in combination with HTML. The following code uses the correct single quotes:
$html = ($add_cta == "Yes" ? .
'<a class="button" href="'.strip_tags(trim($a_href)).'">'.
strip_tags(trim($a_title)).
'</a>'. : '');
return $html;
Or just use an if statement:
$html = '';
if ($add_cta == "Yes")
{
$href = strip_tags(trim($a_href));
$title = strip_tags(trim($a_title));
$html .= ' <a class="button" href="'.$href.'">'.$title.'</a>';
}
return $html;
try this. You have done some concatenation mistakes which I have fixed
$a_href = "stackoverflow.com";
$a_title = 'Anything';
$html =
($add_cta == "Yes" ?
' < a class = "button" href = "'.strip_tags(trim($a_href)) .
'" > '.strip_tags(trim($a_title)) .
' < /a>' : "")
;
echo $html;
I think the most simple/readable way to do this is by using a separate template which returns the rendered link.
link-template.php
<?php
return '' . strip_tags(trim($a_title)) . '';
The method/function you want to use this template on:
return $add_cta === 'Yes' ? include 'link-template.php' : '';
What you should consider would be to define $a_href and $a_title before including the template

If statement in foreach loop for printing an array [duplicate]

I want to concatenate in the middle of an echo to write an if statement, is this possible? Here is what I have.
echo "<li class='".if ($_GET["p"] == "home") { echo "active"; }."'><a href='#'>Home</a> </li>";
Like this, using the ternary operator:
echo "<li class='". (($_GET["p"] == "home") ? "active" : "") . "'><a href='#'>Home</a> </li>";
echo "<li class='".(($_GET["p"] == "home") ? "active" : "")."'><a href='#'>Home</a> </li>";
Do like this:
echo "<li class='".($_GET["p"] == "home" ? 'active' : '') ."'><a href='#'>Home</a> </li>";
Instead of messy inline concatenations, might I suggest getting cozy with printf()?
$format = '<li class="%s">Home </li>';
printf($format, ($_GET['p'] == 'home') ? 'active' : '');

How do I code an IF statment within a string?

I've tried every combination I could think of, but nothing is working. How do I integrate an IF statement within a string?
This is the line I need integrated;
if ($row['SL'] == 'Yes') {echo '<li class=\"sl\">Short Sale</li>' ;}
This is what I tried;
elseif ($row['X'] == 'sold') { echo "
<li id=\"price\"> $ {$row['SP$']}</li>
" .
{ if ($row['SL'] == 'Yes') {echo '<li class=\"sl\">Short Sale</li>' ;} }
. "
<li>Days on Market: {$row['DOM']}</li>;
}
Use a ternary operator:
elseif ($row['X'] == 'sold') { echo "
<li id=\"price\"> $ {$row['SP$']}</li>
" . ($row['SL'] == 'Yes') ? '<li class="sl">Short Sale</li>' : ''
. "
<li>Days on Market: {$row['DOM']}</li>";
}
You just need to break it up:
elseif ($row['X'] == 'sold') {
echo "<li id=\"price\"> $ {$row['SP$']}</li>";
if ($row['SL'] == 'Yes') {
echo '<li class=\"sl\">Short Sale</li>';
}
echo "<li>Days on Market: {$row['DOM']}</li>;
}
You don't. You output the first half the string, then fully stop that statement, then evaluate your if, then output the rest of the string.
...
elseif ($row['X'] == 'sold') {
echo "<li id=\"price\"> $ {$row['SP$']}</li>";
if ($row['SL'] == 'Yes') {
echo '<li class=\"sl\">Short Sale</li>'
}
echo "<li>Days on Market: {$row['DOM']}</li>";
}
You can't "embed" an if statement in a string, firstly because that's not syntactically valid, but even if it was, if statements don't resolve to a value in PHP.
What you are looking for is called Ternary Operator or Shorthand If/Else:
( condition ? true result : false result )
Example:
echo "<li id=\"price\">{$row['SP']}</li>" . ( $row['SL'] == 'Yes' ? '<li class="sl">Short Sale</li>' : '' ) . "<li>Days on Market: {$row['DOM']}</li>";
The above example is the same as:
echo "<li id=\"price\">{$row['SP']}</li>";
if ( $row['SL'] == 'Yes' ) echo '<li class="sl">Short Sale</li>';
else echo '';
echo "<li>Days on Market: {$row['DOM']}</li>";
You can "stack" ternary expressions so the complete example will look like:
echo
$row['X'] == 'sold'
? "<li id=\"price\">{$row['SP']}</li>" .
( $row['SL'] == 'Yes' ? '<li class="sl">Short Sale</li>' : '' ) .
"<li>Days on Market: {$row['DOM']}</li>"
: '';
important: you cannot build a ternary operator without else statement.

PHP Display option depending on value

I am editing a part of a script that displays gender of a person but trying to add additional options.
The form that saves the information saves it as a value.
In my lang file this is what i have got related to the part i am trying to change :
$LNG['powner'] = 'Pet Owner';
$LNG['dog'] = 'Dog';
$LNG['cat'] = 'Cat';
$LNG['rabbit'] = 'rabbit';
The part of the code im trying to display is
((!empty($profile['gender'])) ? '<div class="sidebar-list">'.$LNG['ttl_gender'].':
<strong>'.(($profile['gender'] == 1) ? $LNG['powner'] :($profile['gender'] == 2) ?
$LNG['cat'] : ($profile['gender'] == 3) ? $LNG['rabbit'] : $LNG['rabbit']).'</strong>
</div>' : '').'
But it will only display cat or rabbit ...
I am thinking that the code is set to be one or the other because this works :
((!empty($profile['gender'])) ? '<div class="sidebar-list">'.$LNG['ttl_gender'].'
: <strong>'.(($profile['gender'] == 1) ? $LNG['dog'] : $LNG['cat']).'</strong></div>'
: '').
after the code if follows
'.((!empty($profile['website'])) ? '<div class="sidebar-list">'
.$LNG['profile_website'].': <strong><a href="'.$profile['website'].
'" target="_blank" rel="nofllow">'.$LNG['profile_view_site'].'</a>
</strong></div>' : '').'
Your code could be re-written to say:
if(!empty($profile['gender']) {
echo '<div class="sidebar-list">'.$LNG['ttl_gender'];
} else {
echo "<strong>";
if($profile['gender'] == 1) {
echo $LNG['powner'];
} else {
if($profile['gender'] == 2) {
echo $LNG['cat'];
}
else {
if($profile['gender'] == 3){
echo $LNG['rabbit'];
} else {
echo $LNG['rabbit'];
}
}
}
}
As you see the code using shorthand If/Else statements is confusing to read, and can lead to mistakes. Re-write your functionality in more readable way, and you will prevent errors, and confusion with regards to what the actual conditions should be.
I'm assuming that the problem you're having is that the users you're testing this on are either gender 2 or 3, and never 1.

Active Page for CSS using PHP and MYSQL

I am trying to build a menu with an active page element for CSS using PHP and MySQL.
This example PHP/HTML hybrid works, and is what I'm trying to mimic.
<nav><ul>
<li<?php if ($thisPage == "1") echo " class=\"active\""; ?>>page 1</li>
<li<?php if ($thisPage == "2") echo " class=\"active\""; ?>>page 2</li>
<li<?php if ($thisPage == "3") echo " class=\"active\""; ?>>page 3</li>
</nav></ul>
I want to blend this statement to set the active class:
<?php if ($thisPage == $menuID) echo " class=\"active\""; ?>
Into this unordered list statement
<?php
echo "\n<nav>\n";
echo "<ul>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu))
{
echo "<li>" . "" . $row_rsMenu['menuName'] . "</li>\n";
}
echo "</ul>\n";
echo "</nav>\n";
?>
This is where I am but I can't seem to get the syntax to work correctly.
echo "<li" . "if(" . $thisPage==$menuID . ")". echo ' class=\"active\"';" . ">" . "" . $row_rsMenu['menuName'] . "</li>\n";
If someone could help me to understand where this went wrong I'd appreciate it.
You have your if statement encapsulated in quotes. That means that PHP won't interpret it. Instead, it will print it out along with your HTML.
Something along the lines of this will work better:
echo "\n<nav>\n";
echo "<ul>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu))
{
$active = ""; //not active by default
if($thisPage==$menuID){
$active = ' class="active" ';
}
echo "<li>" . "" . $row_rsMenu['menuName'] . "</li>\n";
}
echo "</ul>\n";
echo "</nav>\n";
By the way, where are you getting $menuID from?
Your error is wrapping the if block within quotes, among a few other issues with quotes.
Try this instead:
echo '<li', (($thisPage==$menuId) ? ' class="active"' : ''), '>', '', $row_rsMenu['menuName'], '</li>';
This uses a ternary operator to shorten things up a bit, in addition to fixing your syntax error.

Categories