In this code the variable $controller has been initialized and used (code is from Prestashop v1.6)
$current_index = 'index.php'.(($controller = Tools::getValue('controller')) ? '?controller='.$controller : '');
What counts as not true in this if block? How is this block evaluated?
Is this considered best practice?
$current_index will equal the string index.php if Tools::getValue('controller') evaluates to false.
If you convert the block into a non-ternary operation you can see the assignment clearer:
$controller = Tools::getValue('controller');
if ($controller) {
$parameter = '?controller=' . $controller;
} else {
$parameter = '';
}
$current_index = 'index.php' . $parameter;
Ternary operations are best practice, but in the example code you've provided it's not entirely clear due to both the URL parameter assignment and the ternary operation happening on a single line.
Rewrite it as,
$controller = Tools::getValue('controller');
$current_index = 'index.php'.(($controller) ? '?controller='.$controller : '');
Related
I'm trying to create a simple yes/no or true/false boolean type line to parse content depending on the answer.
Like this:
<?php
dangerous = "yes";
?>
<?php
dangerous = "no";
?>
A block down here similar to isset, that will parse if the answer above is yes, and to not appear if anything else other than yes is written.
<?php if dangerous = yes ?>
Dangerous content here.
<?php endif; ?>
I'm new to PHP, so I'm not sure what route to go with here.
Firstly, this line here will always evaluate to true, because you are using a single = which is an assignment operator:
if($dangerous = 'yes') // this will always be true
You need to use == for a comparison operator, or === for strict comparison which takes variable types and values into consideration as well. For more info on the difference between the comparison operators, see here.
The way you're doing it currently is pretty widely used, but is not the best practice. Your variable $dangerous will be set every time, and you need to check for the value of it to determine whether to evaluate your conditions or not:
if($dangerous == 'yes') {
// do dangerous stuff
}
Better practice, as you've said, is to use a boolean variable which will evaluate to true or false (above example in this same test will evaluate to true in both cases):
$dangerous = true; // or false;
if($dangerous) {
// do dangerous stuff
}
Likewise, if it's not dangerous:
if(!$dangerous) {
// pretty safe, but this will evaluate to true for false, null, zero etc
}
In this example, !$dangerous will evaluate to true when $dangerous is null, zero etc, so if you need a strict comparison for the value of false, you'll need the === comparison operator:
if($dangerous === false) {
// false evaluates to true when comparing for a false value
// false evaluates to false when comparing for a null value
}
Better to use a boolean variable over a string representation of a result in most cases. Something to keep in mind though is that if your your boolean variable represents the return of a function call, it might not always be consistent.
if($dangerous == "yes"){
//do something
} else {
//do something else
}
<?php
if($yes){
?>
<b>This is my HTML.</b>
<?php
}else{
?>
<b>This is other HTML.</b>
<?php
}
?>
<?php if ($dangerous === 'yes'): ?>
yes
<?php endif; ?>
<?php if ($dangerous == 'no'): ?>
no
<?php endif; ?>
The issue is the use of an assignment operator (=) when you should be using a comparison operator (== / ===) and comparing variables and value correctly.
For your case
<?php
if($dangerous === "yes"){
//Dangerous content here.
}
?>
Use code like this:
$dangerous = true; // or false if no
// check result
if ($dangerous) {
// dangerous!
}
Define the conditions for dangerous content and apply php expeptions:
if(dangerous){
try {
echo inverso(5) . "\n";
echo inverso(0) . "\n";
} catch (Exception $e) {
echo 'Excepción capturada: ', $e->getMessage(), "\n";
}
}
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
if ($form->isValid()) {
// ... perform some action, such as saving the task to the database
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
return $this->redirect($this->generateUrl($nextAction));
}
Here is the link to the documentation
http://symfony.com/doc/current/book/forms.html
The class documentation says that it returns a bool.
What is the point of
? 'task_new'
: 'task_sucess';
That is called "ternary" and it's awesome:
This is assigning the value $nextAction based on a condition. The first part (after the =) is the condition, like an if statement, the second part (after the ?) is the value assigned if the condition is true, and the last part (after the :) is the value assigned if the condition is false.
//the condition
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new' //true value
: 'task_success'; //false value
It is a shorter way of writing this:
if ($form->get('saveAndAdd')->isClicked()) {
$nextAction = 'task_new';
}
else {
$nextAction = 'task_success';
}
So, here's some easy examples:
$foo = (true) ? 'True value!' : 'False value!';
echo $foo; //'True value!' of course!
$foo = (false) ? 'True value!' : 'False value!';
echo $foo; //'False value!' of course!
It's the Ternary operator. The syntax is as follows:
value = (condition) ? run if true : run if false;
In this case, if $form->get('saveAndAdd')->isClicked() is true, then task_new. Else task_success.
If could be rewritten like so:
if($form->get('saveAndAdd')->isClicked()) {
$value = "task_new";
} else {
$value = "task_success";
}
The ternary operator is a shorter form for an if statement.
The : is the "else" part.
Example in Java:
boolean bool;
true ? bool = true : bool = false;
It's a senseless example, but shows the ternary operator very well.
if the condition, here true is "true", then fill into the variable bool true, else false.
alternative if-statement in Java to the code example above:
boolean bool;
if(true)
bool = true;
else
bool = false;
This is a Ternary Operator which is a short hand if else statement. This is equivalent to
if($form->get('saveAndAdd')->isClicked()){
$nextAction = 'task_new'
else{
$nextAction = 'tassk_success'
}
This is the ternary opeator, a short-hand expression that works the same as an if
$value = someFunc() ? "whatever" : "the other"
is equivalent to
if (someFunc()) {
$value = "whatever";
} else {
$value = "the other";
}
This is equivalent to "if" and "else" statements.
This code :
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
is equivalent to this code :
if ( $form->get('saveAndAdd')->isClicked() )
{
$nextAction = 'task_new';
}
else
{
$nextAction = 'task_success';
}
I know there is a shorthand for IF/ELSE STATEMENT in PHP such as
($user['permissions'] == 'admin' ? true : false);
But is there a shorthand for ELSE IF statement besides switch?
What you could do
You can keep chaining ternary operators together, e.g.:
$x = $condition1 ? true : ($condition2 ? true : false);
It looks nice now, but once your conditions grow bigger, it quickly becomes unreadable. Note that parentheses are bare essentials for these kind of expressions.
What you should do
Once you add more conditions, prefer to use the proper branching syntax; always assume the person who later has to take over your code is a psychopath who knows where you live:
$canAccess = false;
if ($user['permissions'] == 'admin') {
$canAccess = true;
} elseif ($user['permissions'] == 'whatever') {
$canAccess = true;
}
Yes, you could use an or in the first statement too.
Or, a switch:
switch ($user['permissions']) {
case 'admin':
case 'whatever':
$canAccess = true;
break;
default:
$canAccess = false;
}
I’d rather just use elseif() {} anyway
$somevalue == 'foo' ? 'is foo' : ($somevalue == 'bar' ? 'is bar' : 'is neither');
I'd love to know what this means so I can google it as I see it all the time and it seems to be very useful
(($winstate==1)?'X':'O')
edit: The vars are irrelevant.
Thanks guys
That's called a ternary operator, it's PHP's only ternary operator, and it's shorthand for a conditional:
if($winstate == 1){
return 'X';
}else{
return 'O';
}
It's frequently used when the conditional test results in an assignment or returns something, in this case suppose you wanted to assign 'X' or 'O' to a variable $move, it's far more concise to write:
$move = ($winstate == 1) ? 'X' : 'O';
Look at Comparsion Operators
There's everything explained
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
I'm new to PHP. I came across this syntax in WordPress. What does the last line of that code do?
$page = $_SERVER['REQUEST_URI'];
$page = str_replace("/","",$page);
$page = str_replace(".php","",$page);
$page = $page ? $page : 'default'
That's the ternary operator:
That line translates to
if ($page)
$page = $page;
else
$page = 'default';
It's an example of the conditional operator in PHP.
It's the shorthand version of:
if (something is true ) {
Do this
}
else {
Do that
}
See Using If/Else Ternary Operators
http://php.net/manual/en/language.operators.comparison.php.
It's a ternary operation which is not PHP or WordPress specific, it exists in most langauges.
(condition) ? true_case : false_case
So in this case the value of $page will be "default", when $page is something similar to false — otherwise it will remain unchanged.
It means that if $page does not have a value (or it is zero), set it to 'default'.
It means if the $page variable is not empty then assign the $page variable on the last line that variable or set it to 'default' page name.
It is called conditional operator
More verbose syntax of the last line is:
if ($page)
{
$page = $page;
}
else
{
$page = 'default';
}
That's the so-called conditional operator. It functions like an if-else statement,
so
$page = $page ? $page : 'default';
does the same as
if($page)
{
$page = $page;
}
else
{
$page = 'default';
}