What is this syntax in PHP? - php

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;

Related

PHP Shorthand If/Else when using return

There are few nice ways to write shorthands in PHP.
Less common but shortest example:
!isset( $search_order ) && $search_order = 'ASC';
More common but a little longer:
!isset( $search_order ) ? $search_order = 'ASC' : $search_order = NULL;
We can even combine examples above in to an amazing shorthand:
!isset( $_POST['unique_id'] ) && preg_match( '/^[a-zA-Z0-9]{8}$/', $_POST['unique_id'] ) ? $post_unique_id = $_POST['unique_id'] : $post_unique_id = NULL;
But how do we use examples above with functions and return, example:
function filter_gender_request($data) {
preg_match('/(fe)?male/i', $data, $data);
isset($data[0]) && return $data[0]; // It doesn't work here with return
}
At the same time, if I state the following, instead of isset($data[0]) && return $data[0]; then everything works as expected:
if (isset($data[0]) ) {
return $data[0];
}
What am I doing wrong here? If the very first and shortest example works outside of function flawlessly, why then it doesn't work with return?
Is there a possibility to use shorthands with return?
With your current syntax, what do you expect your function to return when $data[0] is not set? Surely you don't expect your function to not return anything, depending upon a condition.
The only alternative I see is the ternary operator, where you return something other than $data[0] when it is not set:
return isset($data[0]) ? $data[0] : null;
For future googlers.
Use php 7 null coalesce (??) operator
return $data[0] ?? null;
Your amazing shortcut is actually rather hideous code. You are abusing the ternary operator, and that code is actually far LESS readable AND less maintainable than if you'd written it out. People expect ternaries to perform a test and return an either/or value. Performing assignment within it is NOT normal behavior.
The problem with your code is you are trying to execute a return statement as part of the ternary expression. The ternary operator generally results in an assignment as in:
$message = is_error() ? get_error() : 'No Errors';
This results in an assignment to $message based on the return value of is_error(). Your code is trying to process a program control statement within the operation. return cannot be assigned to the variable.
For this reason, what the other users have posted are better options for your situation.
oke I don't know what you are doing but this should work:
return ( isset($data[0]) ? $data[0] : false);
Agreeing with what has been answered here, that shorthand is harder to read once you've gone away from it and come back, or worse, another developer in the future.
Imagine yourself with even a small 500 line script file, with 40 lines of shorthand elseif as you use it, would you be ok trying to add or change code?
Especially when the subject or content is not something you're familiar with, it becomes a headache to debug or make additions.
This is much more manageable and doesn't matter what it's about, it's just code:
if ($var == 'unicorns')
{
$this->remove_horn;
}
elseif ($var == 'horse')
{
$this->glue_on_horn;
}
else
{
$this->must_be_a_zebra;
}
just saying

PHP : tell php if xxx else do nothing

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.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

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']);

The use of "?" and ":"

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

How to reduce the number of if-else statements in PHP?

I found that there are many if-else statements, especially nested if else statements, these statements make my code less readable. How to reduce the number of if else statements in PHP?
My tips are as follows:
1.Use a switch statement when it is suitable;
2.use exit() statement when it is feasible;
3. Use ternary statement when it is feasible;
Are there other tips that can reduce if else statements, especially nested if-else statements?
Try to use "early return" when possible in order to reduce nesting depth. Try to use boolean expression evaluation.
Example:
function foo($param)
{
$ret = false;
if(userIsLoggedIn()) {
if(is_array($param)) {
if($param['count'] > 0) {
$ret = true;
}
else {
$ret = false;
}
}
}
return $ret;
}
You could rewrite this like:
function foo($param)
{
if(!userIsLoggedIn()) return false;
if(!is_array($param)) return false;
return $param['count'] > 0;
}
Refactor your code into smaller work units. Too much conditional logic is a code-smell and usually indicates that your function needs to be refactored.
There is an official academic method to refactor and simplify a lot of if conditions, called Karnaugh mapping.
It takes in multiple test conditions and attempts to assist in creating simplified if statements that cover all the required cases.
You can learn more about it from wiki here.
Use the ternary operator, refactor your code, write a function or a class which does all the necessary if else statements.
I work on a lot of code thats full of ever evolving business logic and needs to be modified every other day. Two tips that's certainly helped me keep up with the modifications are: avoid all else statements and return/exit as soon as possible. Never get into deep nesting -> create sub routines/functions.
Replacing all else statements with negated if statements makes your code much easier to read top to bottom (the proximity of the condtion and the code block):
# business logic block
if ( $condition ) {
# do something
# code code code
} else {
# code code code
return;
}
# refactored:
if ( ! $contition ) {
# code code code
return;
}
if ( $condition ) {
# code code code
}
Secondly, return/exit as soon as possible. My opinion of course, but I don't see the point in running through any extra conditions/tests when once you've already determined the result of the subroutine, especially when you would like to read the code top to bottom. Removing all ambiguity makes things simpler.
To conclude, I like to avoid using else especially in long lists of BL. Return as soon as you know the result. If the nesting level is more than 2, create sub routines/functions.
polymorphism could get rid of a few as well, allthough harder to implement to reduce if/else in PHP as it is not type safe...
You can reduce the number of if/else codes by using ternary operator or null coalescing operator like this:
Using the ternary operator:
Variable = (Condition) ? (Statement1) : (Statement2);
$age = 20;
print ($age >= 18) ? "Adult" : "Not Adult";
Output:
Adult
By using the null coalescing operator:
// fetch the value of $_GET['user'] and returns 'not passed'
// if username is not passed
$username = $_GET['username'] ?? 'not passed';
print($username);
print("<br/>");
// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
print($username);
print("<br/>");
// Chaining ?? operation
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
print($username);
Output:
not passed
not passed
not passed

Categories