Let's say we have the following array:
$ourArray = [
'a' => 'a',
'b' => 'b',
];
And we try to get the value of key 'c'
(which does not exist):
$someValue = $ourArray['c'] ?? null;
So, the previous statement will not throw any notice since it is just syntactic sugar to isset
. To more information please visit PHP site.
In PHP7.1 was introduced symmetric array destructuring, so the idea is to destructure the array avoiding notices, so for example:
[
'c' => $someValue
] = $ourArray;
So this will throw Undefined index: c in $ourArray ...
.
So, is there any way to avoid PHP to throw a notice using symmetric array destructuring? And without using functions like error_reporting
or ini_set
.
Sadly, php only supports a very limited bit of destructuring, specifically, when destructuring arrays, by using list() destructuring or [] destructuring. So as long as you are dealing with an array or an associative array you can do some destructuring.
Object Destructuring (PHP 7.1) Unfortunately there is no object destructuring. However you can convert an object to an associative array using get_object_vars , and then use associative array destructuring.
Using array destructuring on any iterableNon-iterables cannot be destructured as arrays.
You can use the @
operator.
https://secure.php.net/manual/en/language.operators.errorcontrol.php
@[
'c' => $someValue
] = $ourArray;
Disclaimer
This operator is controversial. It may hide useful errors messages from function calls. A lot of programmers will avoid it even for hight cost. For assignments it is safe though.
Based on comment by h2ooooooo.
If You can and want define all defaults, You can use code below.
[
'c' => $someValue
] = $ourArray + $defaults;
The operator +
is important. The function array_merge
will not preserve numeric keys.
The definition for $defaults
may look like this. You have to define values for every possible key.
$defaults = [
'a' => null,
'b' => null,
'c' => null,
'd' => null,
'e' => null,
'f' => null,
];
# or
$defaults = array_fill_keys(
['a', 'b', 'c', 'd', 'e', 'f'],
null
);
You could try:
[
'c' => $someValue
] = $ourArray + ['c' => null];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With