How can I decide css class name dynamically in PHP ? - php

I want to decide a css class dynamically using ternary operator in PHP,I'm using following code but its some error
echo '<div '.count($photos) > 1 ? "class='slider'" : "class='image'".'>';
what's wrong in above code ?

You need parentheses for the expression.
echo '<div ' . (count($photos) > 1 ? "class='slider'" : "class='image'") . '>';
Or
echo '<div class="' . (count($photos) > 1 ? 'slider' : 'image') . '">'

Related

inserting a variable within another variable string that contains an if statement

I have a string as follows and store it in the variable:
$div = '<div class="posts"> . $row['author'] .'<?php if('.$perm.'>1):?><br>  '.$role.'</br>  Edit<?php endif ?></div>
What I want is to use this variable in another page so I need to insert the if statement to regulate permission so the content only displays with those users with above 1. It comes up with no syntax errors but when I run it this happens
John1):?>
Moderator
Edit
so the 1):?> is being displayed when it shouldn't.
Any reasons why? or how I could do this better?
Thanks.
Can you give an try like this:
$div ='<div class="posts">'.$row['author'].''; ?> <?php if($perm>1) {'<br>  '.$role.'</br>  Edit';} ''
I think its badly formated with single quotes ' , please check and lets see if it is.
Try conditional operator like this. The div section is kept at both statements just to improve readability.
$div = if('.$perm.'>1) ? ('<div class="posts"> . $row['author'] . <br>  '.$role.'</br>  Edit<div>') : ('<div class="posts"> . $row['author'] .'<div>');
Or:
$div = '<div class="posts"> . $row['author'] .';
$div += if('.$perm.'>1) ? '<br>  '.$role.'</br>  Edit<div>' : '<div>';

Concatenate PHP inside of echo [duplicate]

This question already has answers here:
if block inside echo statement?
(4 answers)
Closed 8 years ago.
I've attempted to add an if/else statement within an already opened echo function, but page comes up blank. Not too sure if I am concatenating properly.
echo '<span class="year-tab-'.$x.' '.if ($single_year==$year_selected) { echo "" } else { echo "display-none" }.' ">';
You cannot have control structures inside concatenation
$style = ($single_year==$year_selected) ? '' : "display-none";
echo '<span class="year-tab-'.$x.' '.$style.'">';
That concatenation is a bit messy. printf() might be a bit cleaner
printf('<span class="year-tab-%s %s">',
%x,
($single_year==$year_selected) ? '' : "display-none"
);
Or you can do this:
echo '<span class="year-tab-'.$x.' '.($single_year==$year_selected ? "" : "display-none").' ">';
See Ternary Operator on this page.
Using the ternary operator:
echo '<span class="year-tab-'.$x;
echo ($single_year==$year_selected)? '>' : ' style="display:none">';
Note that for display value, you have to enclose it inside the display tag.

if statement to verify page id

I'm trying to add a class="active" statement to a dynamic li element based on if it's meets a requirement of a pageID being equal to a variable named thisPage but I have the syntax messed up. My problem is how do I add my if statement into the middle of a string? I think I have the spirit captured below....
Thanks
<? ...........
$menu .= "\t<li" . ' if $thisPage=={$pageID} echo class="active"' . ">{$pval['menuTitle']}</li>\n";
...........
?>
You can use a ternary
$menu .= '<li'.($thisPage==$pageID?' class="active"':'').'></li>';
Try this
$menu .= "\t<li".($thisPage==$pageID ? ' class="active"' : '').'>'.$pval['menuTitle'].'</li>'."\n";
Though I'd recommend using sprintf to make what's going on clearer
$menu .= sprintf('\t<li%s>%s</li>',
($thisPage==$pageID ? ' class="active"' : ''),
$pval['link'],
$pval['menuTitle']);
easiest way would be to use a ternary operator like this:
$menu .= "\t<li" . $thisPage=={$pageID} ? 'class="active"' : '' . ">{$pval['menuTitle']}</li>\n";

PHP echo formatting of html

I am trying to echo out multiple table rows on my sql query and provide them with alternating colors to improve the aesthetic value of my site. I am fairly new to php and I am extremely fussy over the presentation of my code and therefore I would like to include the output html into my PHP block to improve readability.
I have browsed some past threads but I am still rather unclear of how the formatting of a string works in PHP, the code below shows my attempt of formatting the output:
echo '<tr class=" . 'if( $class_style %2 == 0 ){ echo "row_dark"; } else echo "row_light"' . ">';
What am I doing wrong here?
Regards
Alex.
You can't put an if structure in an echo.Use that :
echo '<tr class="'. ($class_style %2 == 0) ? 'row_dark' : 'row_light' . '">';
It's a ternary operation.
You should use like this right syntax:
echo '<tr class="'.($class_style %2 == 0 ? "row_dark" : "row_light").'">';
It should be
echo '<tr class=" '. instead of echo '<tr class=" .'
<?php echo '<tr class="'.(($class_style %2 == 0)?'row_dark':'row_light').'">';?>
or
<?='<tr class="'.(($class_style %2 == 0)?'row_dark':'row_light').'">';?>

Echo with Shorthand If not behaving properly

I'm programming in PHP, I'm using a 'shorthand if' to echo some HTML code on to the page, but it is behaving in odd ways.
echo '<div id="filter_bar">
<ul>';
echo '<li>Trending</li>' : '>Trending</a></li>';
echo '<li>Most Picked</li>' : '>Most Picked</a></li>';
echo '<li>Newest</li>' : '>Newest</a></li>';
echo '</ul></div>';
The resulting code that I get as a result is this
class="filter_selected">Trending</a></li> class="filter_selected">Most Picked</a></li> class="filter_selected">Newest</a></li>
As you can see, the opening list tags are not showing... but they do if I replace the first period '.' on each line with a ',' comma.
So this works, with the commas
Should I be using a comma here? Everywhere online sheems to show a period '.'
The reason is:
echo '<li>' . true ? 'aaa' : 'bbb'; will give you aaa,
because it is same with '<li>1' ? 'aaa' : 'bbb'
And you should do like this:
echo '<li>' . (true ? 'aaa' : 'bbb');
Maybe you can make your life a bit easier:
echo '<div id="filter_bar"><ul>',
'<li>' : '>', 'Trending</li>',
'<li>' : '>', 'Most Picked</li>',
'<li>' : '>', 'Newest</li>',
'</ul></div>';
Which will use commas (no need to repeat echo that much) and you don't need to repeat strings that much if you only want to insert the class attribute.
Then you made use of parenthesis where they were not needed (see Operator Precedence Docs) but at the place where those are needed, you didn't use them (the last case).
Additionally it's better to fill those values to variables upfront, so you can debug stuff easier (and you don't mix $_GET with output, so to prevent mixing output logic with input variables).
That done you could have learned that your issue is not within the echo but just the expression you've formulated with the ternary operator.
$class_trending = $_GET['select'] == "trending" ? ' class="filter_selected"' : '';
$class_most_picked = $_GET['select'] == "most_picked" ? ' class="filter_selected"' : '';
$class_newest = ($_GET['select'] == "newest") || empty($_GET['select']) ? ' class="filter_selected"' : '';
echo '<div id="filter_bar"><ul>',
'<li><a href="?select=trending"', $class_trending, '>Trending</a></li>',
'<li><a href="?select=most_picked"', $class_most_picked, '>Most Picked</a></li>',
'<li><a href="?select=newest"',$class_newest , '>Newest</a></li>',
'</ul></div>';
dunno your problem but this code looks an ugly mess for me.
I'd make it this way:
in the PHP code I'd prepare variables first.
$sections = array(
'newest' => 'Newest',
'trending' => 'Trending',
'most_picked' => 'Most Picked',
);
if (empty($_GET['select']) OR !$choice = array_search($sections,$_GET['select'])) {
$choice = 'newest';
}
and then in the template run smooth and short loop:
<div id="filter_bar">
<ul>
<? foreach ($sections as $sect => $name): ?>
<li>
<a href="?select=<?=$sect?><? if ($choice == $sect) ?>" class="filter_selected"<? endif ?>><?=$name?></a>
</li>
<? endforeach ?>
</ul>
</div>
One possible solution is
echo "<li><a href='?select=newest'";
echo ($_GET['select'] == "newest" || empty($_GET['select'])) ? ' class="filter_selected">Newest</a></li>' : '>Newest</a></li>';
Change your parentheses to the following:
echo '<div id="filter_bar">
<ul>';
echo '<li>Trending</li>' : '>Trending</a></li>');
echo '<li>Most Picked</li>' : '>Most Picked</a></li>');
echo '<li>Newest</li>' : '>Newest</a></li>');
echo '</ul></div>';
If you do not do this, PHP does not know what exactly your condition is. Also have a look at operator precendence as this explains why it works using commas.
By the way: The ?: is called ternary operator.

Categories