Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid PHP notice when destructuring array

Tags:

arrays

php

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.

like image 929
Manuel Avatar asked Feb 16 '18 12:02

Manuel


People also ask

Can you Destructure in PHP?

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.

How do you deconstruct an object in PHP?

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.

Can you Destructure an array?

Using array destructuring on any iterableNon-iterables cannot be destructured as arrays.


2 Answers

Solution with @

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.

Solution with defaults

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
);
like image 138
Michas Avatar answered Oct 17 '22 04:10

Michas


You could try:

[
    'c' => $someValue
] = $ourArray + ['c' => null];
like image 8
dhinchliff Avatar answered Oct 17 '22 06:10

dhinchliff