Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-statement in a Variable

I want to print the same page's name differently based on a certain variable.

Here is a corresponding code.

$metaTitle ="'if($variable=='input'){ title#1 }else {  title#2 };'";

And the produced meta title is lately used in the same file to create the page title (<title></title>)

But it keeps producing the title like

if($variable=='input'){ title#1 }else {  title#2 };

(the whole if statement as a whole. It does not recognize the if statement. It considers the statement as a plain text.)

What did I do wrong in the sentence??

like image 321
Visualizer7 Avatar asked Jul 08 '26 00:07

Visualizer7


2 Answers

Use ternary operator "?:":

$metaTitle = ($variable=='input')? "title#1" : "title#2";

The first part is the condition:

($variable=='input')

The second is the result when condition is true:

"title#1"

The third is the result when condition is false:

"title#2"

Source http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

like image 125
dpp Avatar answered Jul 11 '26 03:07

dpp


Because you just assign $metaTitle a STRING "'if($variable=='input'){ title#1 }else { title#2 };'" and it's not a runable statement

you should do like this

if ($variable=='input') {
    $metaTitle = "title#1";
} else {
    $metaTitle = "title#2";
}

or simply use Ternary Operator

like image 37
horsley Avatar answered Jul 11 '26 01:07

horsley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!