What's the equivalent of the following (based in JS style) in PHP:
echo $post['story'] || $post['message'] || $post['name'];
So if story exists then post that; or if message exist post that, etc...
It would be (PHP 5.3+):
echo $post['story'] ?: $post['message'] ?: $post['name'];
And for PHP 7:
echo $post['story'] ?? $post['message'] ?? $post['name'];
There is a one-liner for that, but it's not exactly shorter:
echo current(array_filter(array($post['story'], $post['message'], $post['name'])));
array_filter would return you all non-null entries from the list of alternatives. And current just gets the first entry from the filtered list.
Since both or and || do not return one of their operands that's not possible.
You could write a simple function for it though:
function firstset() {
$args = func_get_args();
foreach($args as $arg) {
if($arg) return $arg;
}
return $args[-1];
}
As of PHP 7, you can use the null coalescing operator:
The null coalescing operator (??) has been added as syntactic sugar
for the common case of needing to use a ternary in conjunction with
isset(). It returns its first operand if it exists and is not NULL;
otherwise it returns its second operand.
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
Building on Adam's answer, you could use the error control operator to help suppress the errors generated when the variables aren't set.
echo #$post['story'] ?: #$post['message'] ?: #$post['name'];
http://php.net/manual/en/language.operators.errorcontrol.php
You can try it
<?php
echo array_shift(array_values(array_filter($post)));
?>
That syntax would echo 1 if any of these are set and not false, and 0 if not.
Here's a one line way of doing this which works and which can be extended for any number of options:
echo isset($post['story']) ? $post['story'] : isset($post['message']) ? $post['message'] : $post['name'];
... pretty ugly though. Edit: Mario's is better than mine since it respects your chosen arbitrary order like this does, but unlike this, it doesn't keep getting uglier with each new option you add.
Because variety is the spice of life:
echo key(array_intersect(array_flip($post), array('story', 'message', 'name')));
Related
<?php
$glass= "water";
$bottol;
if(isset($glass)){
echo $glass;
}elseif(isset($bottol)){
echo "Empty Bottol";
}
echo PHP_EOL;
Ternary Operator is bellow
$demo = isset($glass) ? $glass : $bottol;
echo $demo;
But how can I echo the $glass variable as like as if/else statements inside the ternary operator?? Is it possible? Also, how can I return the $glass variable inside the ternary operator? Like:
return $glass
how can I echo the $glass variable
echo $demo = (isset($glass)) ? $glass : $bottol;
If you want to just simply echo $glass or "Bottl Empty" (you don't mention that testing $bottl is also a requirement so I'll assume your main goal is to echo "Bottl Empty) you have a few options that are a bit cleaner:
<?php
$glass= "water";
$bottol;
echo isset($glass) ? $glass : 'Empty Bottol';
echo PHP_EOL;
It gets even better though since you're just checking to see if a variable is set. When this is the case you can use the "Null Coalescing Operator" - Note: this requires PHP >=7.0
It's like the ternary operator but the lefthand operand checks the variable for null values similar to isset(). It's
useful for checking values and assigning default values.
It works by giving you back the variable's value, if the
variable is set/not null, or conversely, the value of the righthand operand if the variable you're checking is
null.
General example:
$checkthisvariable ?? 'default value';
For you this would simply be:
echo $glass ?? 'Empty Bottol';
I want to simplify my PHP code, and while I find the coalesce operator extremely useful, I don't know if / how I can use it when calling a function from an object.
For example,
$message = $error_msg ?? 'No error message';
Works, but:
$message = $exception->getMessage() ?? 'No error message';
Doesn't. I end up having to resort to:
$message = isset($exception) ? $exception->getMessage() : 'No error message';
Is there any way to make something like the second line of code work, or is the third example the only way to do it?
Apologies in advance for not knowing the proper terminology for asking this kind of question. That might be why I couldn't find an answer.
EDIT: The code I wrote was just an example; this is a general question. For example, let's assume I have a template used both for creating and editing users. The User object has a getName() function that returns their name.
When creating a new user, the 'name' input should be empty. When editing a user, the 'name' input should be filled with the user's name. Of course, $user isn't set in the former, but it's set on the latter.
Having <input value="<?php $user->getName() ?? '' ?>"> would be perfect, but throws an error. <input value="<?php isset($user) ? $user->getName() : '' ?>"> works, but I find the former more readable, so I would like to know if there's a way to make it work.
I know that $user->name ?? '' works, but for some data functions are necessary / preferable.
the problem that ?? and ? working not as you expected;
see example:
<?php
$string = "";
var_dump($string ?? 'ups'); // output ""
var_dump($string ? $string : 'ups'); //output "ups"
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand. manual
so it means:
$string ?? 'ups' is equal to isset($string) && $string !== null which is true for an empty string
and
$string ? $string : 'ups' is equal to $string == true ? $string : 'ups' which is false for empty string
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 want to get a value from the session, but use a default if it is not defined. And ofcourse I want to circumvent the PHP notice.
You can write a function that does this
function get(&$var, $default){
if(isset($var)) return $var;
return $default;
}
echo get($foo, "bar\n");
$foobar = "foobar";
echo get($foobar, "ERROR");
Example in action
Is there a way to do this without defining this function in every file?
You can define it in one script and then require_once that script in your other scripts
You could also just use the ternary operator:
$myVar = isset($var)?$var:$default;
From PHP 7, you can now use the null coalescing operator :
$var ?? $default
that does exactly like your function
Use this concise alternative:
isset($myVar) || $myvar=$default;
The || operator is short circuit, it will not evaluate second operant if the first one be evaluated true.
The Null coalescing operator has been added to PHP version 7.0, what it does is replaces
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
with a shorter version:
$username = $_GET['user'] ?? 'nobody';
What the line above does, is check if $_GET['user'] is set, and not null, then it will assign that to the $username variable, if $_GET['user'] is not set (and thus null) it will default to the 'nobody' string so $username is nobody.
Your code should look like:
echo $foo ?? "bar\n";
$foobar = "foobar";
echo $foobar ?? "ERROR";
Use less code to do what you need.
You don't need to specify the variable again using the _?_:_ format.
echo $var?:"default";
Is the same as
echo $var?$var:"default";
Now as far as an empty check, you could use # to mute notices, I'm not sure of the technical ramifications, but you're already doing your own checking while using this format:
echo #$non_existing_var?:"default";
Some examples:
<?php
$nope = null;
$yup = "hello";
echo ($nope?:$yup) . "\n" ;
echo ($yup?:$nope) . "\n" ;
$items = [ 'one', 'two', false, 'three', 'four', null ];
foreach($items as $item):
echo($item?:"default shown (".var_export($item,true).")")."\n";
endforeach;
echo(#$non_existing?:"default for non-existant variable!");
?>
Output:
$ php variabledefault.php
hello
hello
one
two
default shown (false)
three
four
default shown (NULL)
default for non-existant variable!%
You could use my tiny library ValueResolver in this case, for example:
$myVar = ValueResolver::resolve($var, $default);
and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;
There are also ability to typecasting, for example if your variable's value should be integer, so use this:
$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)
Check the docs for more examples