hey guys , im writing a class and im wondering how i can write a condition statement in this way :
$this->referer= (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';
i need to find my user_id and this is the usual condtion :
if(is_user($user)){
$cookie=cookiedecode($user);
$user_id=intval($cookie[0]);
}
and i think it should be something like this :
$this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0];
but it didnt work
what about this way :
if(is_user($user)){
$cookie=cookiedecode($user);
$this->user_id =intval($cookie[0]);
}
The ternary operator should be used sparingly, and only when the logic is simple enough to maintain readability! Get too complex and the shorthand outweighs its usefulness by being difficult to understand.
The ternary operator will only work with one variable assignement at a time. Here is the manual example
<?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'];
}
Your example
$this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0];
will assign the user_id to cookiedecode($user) if is_user() returns true, or to $cookie[0] if not.
In light of this:
you should keep your existing code structure!!
if(is_user($user)){
$cookie=cookiedecode($user);
$this->user_id =intval($cookie[0]);
}
I didn't see any ELSE statement in your code and i don't understand on why do you want to use short form of conditional statement.
Related
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
What is the name of the following type of if/else syntax:
print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";
I couldn't find any dedicated page in the php manual. I knew that it existed, because I've read a book (last year) with it, and now I found this post.
This is called a ternary expression
http://php.net/manual/en/language.expressions.php
You should note, this is not an "alternate syntax for if" as it should not be used to control the flow of a program.
In the simple example of setting variables, it can help you avoid lengthy if statements like this: (ref: php docs)
// 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'];
}
However it can be used other places than just simple variable assignent
function say($a, $b) {
echo "{$a} {$b}";
}
$foo = false;
say('hello', $foo ? 'world' : 'planet');
//=> hello planet
It's called the ternary operator - although many people call it the "?: operator" because "ternary" is such a seldom-used word.
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']);
Is someone able to explain the meaing of the following statment, and the type of php it is reffering to so I can do further research:
$foo = ($variation_id>0) ? $variation_id : $item_id;
I have tried search but don't really know what i'm searching for.
What I am trying to find out is the name and meaning of the following syntax
? / : and is ($variation_id>0) just a shorthand if statement ?
-- I just stumbled upon conditional variables although a nice simple explanation would still be appreciated.
That structure is called ternary structure and in a short form of If ... Else
Your Snippet:
$foo = ($variation_id>0) ? $variation_id : $item_id;
Converts to
if($variation_id>0) {
$foo = $variation_id;
} else {
$foo = $item_id;
}
Basically, the syntax will come down to something like this
$variable = (<CONDITION>) ? <TRUE EXPRESSION> : <FALSE EXPRESSION>;
You can also combine multiple ternary structure in one line, but it better if you use normal if, if this is over complicated.
That is a ternary condition. If the condition on the left before the '?' is true, it executes the statement after the '?' and before the colon. if not, then it executes the statement after.
In english, this says "use the variation id if it is greater than zero, else use item id"
This is just a shortcut, goes like this:
lets say you have a function.
In the end you want to return a value, but with an exception if the value is 0.
so you will do:
return ($value != 0) ? this_will_be_returned_if_true : this_will_be_returned_if_false;
you can do that also in variable assigning.
Pattern:
(Bool statement) ? true : false;
$foo = ($variation_id>0) ? $variation_id : $item_id;
means
if($variation_id>0)
{
$foo =$variation_id // if true
}
else
{
$foo =$item_id; // if false
}
Let's brake it
$foo=($variation_id>0) ? // This is condition
$variation_id : // This value will be populated by variable '$foo' if condition is true
$item_id; // This value will be populated by variable '$foo' if condition is false
Known as ternary statement/operation, short cut of if else
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;