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).
Related
I can use ?? operator in PHP to handle an index of array which is not defined.
I am confused if null safe operator offers me same or extends ?? operator's functionality?
Edit:
I can do in existing PHP versions to check if there is a specific property is defined in the array:
$user_actions = ['work' => 'SEO','play' => 'Chess', 'drink' => 'coffee'];
$fourth_tag = $user_tags['eat'] ?? "n/a";
I am trying to understand whether null safe operator is offering me something better to do so?
Null coalescing operator (??) work as an if statement it takes two values if first is null then it is replaced by second.
$a = null;
$b = $a ?? 'B';
Here $b will get the value B as $a is null;
In PHP8, NullSafe Operator (?->) was introduced will gives option of chaining the call from one function to other. As per documentation here: (https://www.php.net/releases/8.0/en.php#nullsafe-operator)
Instead of null check conditions, you can now use a chain of calls with the new nullsafe operator. When the evaluation of one element in the chain fails, the execution of the entire chain aborts and the entire chain evaluates to null.
Here is the example from documentation:
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
But in PHP8 you can simply do this:
$country = $session?->user?->getAddress()?->country;
So the working of both operators is significantly different.
<?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';
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' : '' ?>
I am using PHP's null coalescing operator described by http://php.net/manual/en/migration70.new-features.php.
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.
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// 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';
?>
I noticed the following doesn't produce my expected results which was to add a new phone index to $params whose value is "default".
$params=['address'=>'123 main street'];
$params['phone']??'default';
Why not?
You don't add anything to params. Your given code simply generates an unused return value:
$params['phone'] ?? 'default'; // returns phone number or "default", but is unused
Thus, you will still have to set it:
$params['phone'] = $params['phone'] ?? 'default';
The correct answer above from #mrks can be shortened to:
$params['phone'] ??= 'default';
RFC: Null coalesce equal operator
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')));