inserting if statement into css class in html - php

I am trying to insert the following if statement into a class but getting the unexpected T_IF error;
class="color_icon_filter '. if ($link_data['id']==$link_data['text']) {$active} .' "
is this not possible or am I doing it wrong?

You shoud open PHP tags to be interpreted server side.
class="color_icon_filter <?php if ($link_data['id']==$link_data['text']) {echo $active} ?>"
EDIT
Or if you're already in PHP tags
echo 'class="color_icon_filter '.($link_data['id']==$link_data['text'] ? $active : '').'"';

It is not possible to concatenate an if statement onto a string.
You can do this instead:
$string = "123";
if ($bar) {
$string .= "456";
}
$string .= "789";
or this:
if ($bar) {
$baz = "456";
} else {
$baz = "";
}
$string = "123" . $baz . "789";
You could also use a ternary operator, but your if condition is (relatively) long, so it risks making your code look even more like line noise.

You're trying to concat in an if statement.
I'm assuming there's an echo in front of that line. You can either convert that to sprintf (http://php.net/sprintf) or put the if before the echo line, set the value of $active, and then concat in just the variable.
Personally, I think sprintf/printf is your better solution.

You cannot use an if statement in the middle of an assignment operation, but there are ways to achieve your desired result:
$active = '';
if ( $link_data['id']==$link_data['text'] ) {
$active = 'active';
}
$class = "color_icon_filter $active";
or a shorter way via the ternary operator:
$active = ( $link_data['id']==$link_data['text'] ) ? 'active' : '';
$class = "color_icon_filter $active";

Related

PHP String Concatenation (one from variable and another from ternary opeartor) give unexpected results

I am describing the problem by example:
let,
$actual_food['Food']['name'] = 'Tea';
$actual_food['Food']['s_name'] = 'Local';
I am concatenating the aforesaid variables in following way.
$food_name = $actual_food['Food']['name']." ".!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "";
when i print $food_name then the output like ' - Local' but does not print $actual_food['Food']['name'] content.
I think this question is very little bit silly but my curious mind wants to know. Thanks in advance.
You need to take care about concatenation while using ternary operators. You can try as
$food_name = ($actual_food['Food']['name'])." ".(!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "");
echo $food_name;// Tea - Local
Over here I've enclosed the variables within parenthesis ()
Its because of what we call operator precedence. If we don't enclose the ternary operator within parenthesis then your code will be interpreted like as
($actual_food['Food']['name'] . " " . !empty($actual_food['Food']['s_name']) ?...;
So you simply enclose your ternary operator for correct interpretation
Try
$actual_food['Food']['name'] = 'Tea';
$actual_food['Food']['s_name'] = 'Local';
$food_name = !empty($actual_food['Food']['s_name']) ? $actual_food['Food']['name']." - ".$actual_food['Food']['s_name'] : $actual_food['Food']['name'];
echo $food_name;
OR
Add () before and after !empty condition like
$food_name = $actual_food['Food']['name']." ".(!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "");

PHP compare strings error

I am a beginner in PHP and I am trying to separate the input based on the argument. Following is my code but it seems that my $arg variables is never set. Can someone point out my error?
$sender = $_GET['sender'];
$receiver = $_GET['receiver'];
$message = $_GET['message'];
$temp = explode( '.', $message);
$tempcnt = count($temp);
echo $temp[$tempcnt - 1];
if($tempcnt > 2)
{
if($temp[$tempcnt-1] === 'mp4')
{$arg = 3;}
elseif($temp[$tempcnt-1]==='jpg')
{$arg = 2;}
else
{$arg = 1;}
}
echo "Value of arg is" . $arg;
I have even tried with == and === and strcmp in if but still same issue.
Try This:
<?php
$temp strrchr("foo.jpg",".");
if($temp==".mp4")
$arg = 3;
elseif($temp==".jpg")
$arg = 2;
else $arg = 1;
?>
See also the other answers, but one possibility that hasn't been mentioned is that == and === and strcmp all compare case sensitively. So they won't find extensions like .MP4.
The solution in that case would be to use strcasecmp.
However, the first thing to do with problems like this is to output some more diagnostics, so that you can see for yourself what goes wrong. In this example, echo $tempcnt; after its assignment, or else echo "did nothing" after the outer if {..} block.
That way you'll be able to follow what the program flow is.
Issue was caused since i didn't realize i had compared for args > 2. Made it >=2 and viola it done!!
Thanks to #barmar for pointing that out!

php reverse concatenation operator like .=

Don't think this exists but just want to make sure.
Is there a reverse for the .= operator in php.
example:
[$x .= $y] === [$x = $x.$y]
looking for:
[$x ? $y] === [$x = $y.$x]
No, there isn't.
The PHP manual documentation only lists two operators:
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
When you want to prepend to a string, just do $str = $add . $str. There is no need for a "special operator" here. If you use it frequently and don't want to retype it every time, you can create a function like this:
function prepend($text, $add) {
return $add . $text;
}
But, as you can probably guess, it's pointess.
Amal Murali's answer gave me an idea.
function p(&$x,$y){
$x = $y.$x;
return $x;
}
Now instead of having to type out;
$var1 = $var2 . $var1;
You can just do:
p($var1, $var2);
If you send the first variable as reference it does clean the code a bit.
Variables:
$var = ' world';
$var2 = 'Hello';
Usage
echo p($var, $var2);
or
p($var, $var2);
echo $var;
is now equal to:
$var = $var2 . $var1;
echo $var;

improvements in is_array statement before foreach with ternary operator php

I have
if ( is_array($this->input->post("tolerance")) )
foreach($this->input->post("tolerance") as $tolerance)
$tolerances .= $tolerance . " " ;
else
$tolerances = 'Not defined';
I want to short code as we all know we are verifying if it is a an array before getting array values
so what would be the correct way to shorten this?
is_array($this->input->post("tolerance")) ? foreach($this->input->post("tolerance") as tolerance) $tolerances .= $tolerance . " " : $tolerances = 'Not defined';
You should/can NOT shorten this at all while keeping the foreach. The ternary operator is not meant to be used like this. It for expressions, not for statements.
Good example:
$foo = xyz() ? 'foo' : 'bar';
Bad example:
xyz() ? foo() : bar();
Worse example (syntax error):
is_array($foo) ? foreach($foo as $bar) ...
The only proper way to shorten your code is using a temporary variable and implode instead of the loop:
$tolerance = $this->input->post('tolerance');
$tolerance = is_array($tolerance) ? implode(' ', $tolerance) : 'Not defined';
In this case the ternary operator is perfectly fine since now you just have a expressions in the then/else parts instead of statements.
Try with implode(), like this:
$tolerances = is_array($this->input->post("tolerance")) ? implode(' ', $this->input->post("tolerance")) : 'Not defined' ;
I can't think of any good way doing this, but be mean and do a:
/* # == ignore expected warning, $r == assign on testing */
$tolerances = ($r = #implode(' ', $this->input->post("tolerance")) ) ? $r : 'Not defined';
I know, most people see this as bad practice.
Another option, to use foreach:
$tolerances = is_array($arr=$this->input->post("tolerance")) ? call_user_func(function($p) { foreach($p as $t) $ts .= $t . " "; return $ts;}, $arr) : 'Not defined';
just following the 'bad practice' philosophy: if its possible, its meant to be.
$tolerances = ( is_array($this->input->post("tolerance")) == false ) ? "Not defined" : implode(" ", implode($this->input->post("tolerance"))) ;

better PHP variable equals itself

In PHP, is there a better way to say a variable equals itself, example:
$floor = floor($difference / $key);
if($floor > 1) {
$value .= "s";
} else {
$value .= "";
};
On the fourth line, we're saying $floor equals itself plus an empty string. Is there a better way to do this?
Yes.
You can do nothing.
$floor already equals itself. You can remove the entire else block.
Your updated code still doesn't make sense. You're not assigning, you're concatenating. Is this what you meant to do?
if($floor > 1) {
$value = "s";
} else {
$value = "";
}
You can shorten this using the ternary operator:
$value = ($floor > 1) ? 's' : '';
If $value is already an empty string, you don't need to take any action. Not every if statement has to have a matching else.

Categories