want to use PHP Null coalescing operator (??) with comperison - php

if I just want results based on var value set or not? so that I can simply use this
$lab_type=$label['type']??null;
but if want to compare $label['type'] response with using ?? operator, then how to do.
want to change it
<option value="background" <?= isset($label['type'])?$label['type']=='background'?'selected':'':'selected'?> >Background</option>
don't want to use isset here.

Change your ternary operator to:
<?= ($label['type'] ?? null) == 'background' ? 'selected' : '' ?>

Related

How can I write echo and return inside of PHP ternary operator?

<?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';

Simple code explanation

Is this:
$_GET['value'] = isset($_GET['value']) ? $_GET['value'] : '';
same like this:
$_GET['value'] = isset($_GET['value']) ? $_GET['value'] : false;
?
Or is better do a first ? Is there any more variations of this code?
Thanks for any advice!
Nope. They're not the same thing.
The first will return an empty string if the value GET parameter is not set, or return the parameter if it is set.
The second will return false if the parameter is not set.
So you're changing the original $_GET array, which is not really a good idea.
An alternative syntax is the null coalesce operator (??) that would turn your code into this:
$variable = $_GET['value'] ?? ''; //or false, if you want to stick with the boolean.
The ?? operator basically runs isset() on the left expression and returns the first ocurrence of a truthy expression.
If you need to check for an empty string, you should use empty instead of isset.

Using null coalescing operator to echo an escaped output

is there a possiblity to use the null coalescing operator AND echo in one expression like this:
echo htmlspecialchars($_POST['email']) ?? '';
As a short form of
if (isset($_POST['email'])) {
echo htmlspechars($_POST['email']);
}
Any ideas?
The null coalescing operator won't emit a E_NOTICE when a parameter isn't defined.
So you could do $email = htmlspecialchars($_POST['email'] ?? '');
Note that the null coalescing operator is applied to the variable ($_POST['email']) and not to the result of htmlspecialchars().
If you wanted to use conditional ternary operator (?:), then you should have to check if the variable is set before operating on it.
if ( isset($_POST['email']) ) {
$email = htmlspecialchars($_POST['email'] ?: '');
}
Note that isset() will be TRUE if the variable is set (or, in other words, it is defined and has a value different than NULL).

Show the message "N/A" if the $row['gate'] is empty

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.

Using short circuiting to get first non-null variable

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

Categories