I want to use one line and one if statement.
(isset($_COOKIE['uid'])) ? delete_cookie($_COOKIE['uid']) : do_nothing;
but only one condition, else just do nothing. How can I achieve this?
This type of function is probably suited to an if condition
if(isset($_COOKIE['uid'])){ deleteCookie($_COOKIE['uid']); }
But if you wanted to use a ternary operator:
$result = isset($_COOKIE['uid']) ? deleteCookie($_COOKIE['uid']) : null;
if (isset($_COOKIE['uid'])) delete_cookie($_COOKIE['uid']);
If only one statement is executed within an if statement it can be written inline without the need for braces. However I would consider the use of braces for readability
Try with this
if(isset($_COOKIE['uid'])) {
delete_cookie($_COOKIE['uid']);
}
if you want single line statement
(isset($_COOKIE['uid'])) ? delete_cookie($_COOKIE['uid']) : '';
(isset($_COOKIE['uid'])) ? delete_cookie($_COOKIE['uid']) : null;
Probably it will work, if not try to change null to false.
Related
I need to show the message "N/A" if the $row['gate'] is empty. Is it possible to do this using logical symbols ":","?" ?
Like this?
echo (isset($row['gate']) && !empty($row['gate'])) ? $row['gate'] : 'N/A';
PHP 5.3+ allows you to do this.
echo $row['gate'] ?: 'N/A';
That will essentially 'coalesce' an empty value to 'N/A' but if it has a value, it will echo the value.
Ternary operator is commonly used for this kind of validation.
Example while using phps empty()-function:
$output = (!empty($row['gate'])) ? $row['gate'] : 'N/A';
var_dump($output);
(This ofc only checks if the variable is empty, like asked. If you want to check if the variable is defined, use a isset() in there, too).
Yep, it's possible
<?php
$row = array();
echo (empty($row['gate'])) ? 'N/A' : $row['gate'];
?>
yes it is possible with ternary operator
isset($row['data']) ? "your_value" : "N/A";
This is the simplest way.
I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''
I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something } but I don't understand the ?, repeating the get again, the : or the ''. Can someone help break this down for me or at least point me in the right direction?
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
To break it down:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
Or...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
In PHP 7 you can write it even shorter:
$age = $_GET['age'] ?? 27;
This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.
See all new features of PHP 7.
That's called a ternary operator and it's mainly used in place of an if-else statement.
In the example you gave it can be used to retrieve a value from an array given isset returns true
isset($_GET['something']) ? $_GET['something'] : ''
is equivalent to
if (isset($_GET['something'])) {
echo "Your error message!";
} else {
$test = $_GET['something'];
}
echo $test;
Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.
$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.
Ternary:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
If-else:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
It is called the ternary operator. It is shorthand for an if-else block. See here for an example http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? is called Ternary (conditional) operator : example
What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.
if (isset($_GET['something']) == true) {
thing = isset($_GET['something']);
} else {
thing = "";
}
If you want an empty string default then a preferred way is one of these (depending on your need):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
If the url parameter something doesn't exist in the url then $_GET['something'] will return null
strval($_GET['something']) -> strval(null) -> ""
and your variable $value is set to an empty string.
trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
intval() if only numeric values are expected and the default is zero. intval(null) -> 0
Cases to consider:
...&something=value1&key2=value2 (typical)
...&key2=value2 (parameter missing from url $_GET will return null for it)
...&something=+++&key2=value (parameter is " ")
Why this is a preferred approach:
It fits neatly on one line and is clear what's going on.
It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
It's compatible with older and newer php.
Update
Strict mode may require something like this:
$str_value = strval(#$_GET['something']);
$trimmed_value = trim(#$_GET['something']);
$int_value = intval(#$_GET['somenumber']);
I've read through a lot of code where they have if statements, i've noticed other languages use this to. Asp being one.
Tried googling but couldn't find a answer for it.
What exactly does ?: stand for and when to use it.
As far as I'm aware ? is equal to if() and : being equal to }else{.
It is the ternary operator (although in most languages it is better-named as the "conditional operator").
People will often erroneously refer to it as "shorthand if/else". But this is a misnomer; if/else is a statement, ?: is an expression. In most languages, these are distinct concepts, with different semantics.
This is called ternary operator.
It is meant to simplify code in some cases. Consider this:
var str;
if(some_condition)
str = 'yes';
else
str = 'no';
This can be easily rewritten as
var str = some_condition ? 'yes' : 'no';
Your assumption is right.
It is a Ternary operation (Wikipedia)
Essentially, the syntax is condition ? then-expession : else-expression. Typically it is used in assigning variables:
varname = something == 123 ? "yes" : "no";
But it can be used pretty much anywhere in place of a value. It's mostly useful for avoiding repetitive code:
if( something == 123) {
varname = "yes";
}
else {
varname = "no";
}
You could read the documentation. The section you're looking for is titled "Ternary Operator".
You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to check for a possible division-by-zero error before calculating the sin function.
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
from http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.90).aspx
In Java, it's an if/else relationship.
An example of a ternary operation:
boolean bool = (x==1) ? true : false;
http://en.wikipedia.org/wiki/Ternary_operation
I'm working on modifying a script to better suit my needs, and I came across this line in the code:
return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";
I know that the function itself is essentially a cookie getter method, but I'm not quite sure what that syntax (i.e. the "?" and ":") means. I apologize if this is a really dumb question, but could someone explain it to me?
It's a ternary operation and is basically a more compact way of writing an if/then/else.
So in your code sample it's being used instead of having to write:
if (isset($_COOKIE[$parameter_name])) {
return $_COOKIE[$parameter_name];
} else {
return "";
}
It's a ternary operation which is not PHP specific and exists in most langauges.
(condition) ? true_case : false_case
And in my opinion should only be used as short one liners like in your example. Otherwise readabilty would suffer – so never nest ternary operation (though it's possible to do so).
The ? : are the ternary operator. Its a very quick if a then b else c:
if (a) { return b; } else { return c; }
is equivalent to:
return a ? b : c;
return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";
The function return:
$_COOKIE[$parameter_name]
If $_COOKIe with specified parameter_name exists, empty string otherwise.
Prototype:
condition ? this runs if condition true : this runs if condition false;
The code below takes an array value, if it's key exist it should echo out it's value, the ternary if/else part works but the value is not showing up, can anyone figure out why it won't?
$signup_errors['captcha'] = 'error-class';
echo(array_key_exists('captcha', $signup_errors)) ? $signup_errors['catcha'] : 'false';
Also where I have it echo out false, I do not need an output if a key does not exist, should I just delete the word false or is there something else to make the code only show 1 value?
I think you've got a parenthesis in the wrong place:
echo(array_key_exists('captcha', $signup_errors) ? $signup_errors['captcha'] : 'false');
Also, check your spelling of 'captcha'.
You have a typo. This:
? $signup_errors['catcha'] :
Should be this:
? $signup_errors['captcha'] :
catcha -> captcha
I think you meant:
echo(array_key_exists('captcha', $signup_errors) ? $signup_errors['captcha'] : 'false');
Or if you want no output when the key doesn't exist, use an 'if' statement, not the ternary operator:
if (array_key_exists('captcha', $signup_errors)) { echo $signup_errors['captcha']; }
You have misspelled 'captcha' as 'catcha'.