0

I have a setter in which I need to pass a value from an array-element with a specific key.

  • If the array key does not exist pass null
  • If the element value is an empty string '' pass null
  • If the value is not empty string 'string or int or ...' - pass the value

What I have is this:

$obj->setValue(isset($array['a']) ? (!empty(trim($array['a'])) ? $array['a'] : null ) : null );

Some would argue that its hard to read. So - whats the "clean" way?

2
  • $obj->setValue(trim($array['a']) ?: null); . This will throw PHP Notice if key does not exist, but PHP Notice should be suppressed on production environment Commented Jan 24, 2020 at 18:38
  • But " " will be passed as "" though :/ Commented Jan 24, 2020 at 18:43

1 Answer 1

2

You can chain the null coalesce operator (which catches nulls and non-existing keys) with the empty ternary operator (which catches empty values):

$obj->setValue($array['a'] ?? null ?: null);

Example:

$array = [
    'a' => 'foo',
    'b' => '',
];
var_dump($array['a'] ?? null ?: null); // 'foo'
var_dump($array['b'] ?? null ?: null); // null
var_dump($array['c'] ?? null ?: null); // null
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent. I was close to that. But why is $array['b'] working? $array['b'] is existing so it should fire ''. Why is ?: executed though?
?? tests against null, which '' fails, so it passes through. ?: tests against empty, which '' passes so it triggers and returns null instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.