Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Can I wrap an input field with some additional functions when using null coalescing operator in PHP 7?

Let's say I have this trivial example:

$foo = $_REQUEST['foo'] ?? '';

This works beautifully and doesn't throw a notice with undefined index foo when it's not set. Cool. Assuming it's set - I would like to wrap it with additional methods like trim and strtolower.

$foo = strtolower(trim($_REQUEST['foo'])) ?? '';

Can I do this? Will I get the same result? Will foo be trimmed and lower case when exists?

Upvotes: 2

Views: 79

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

The way you've written will result in an undefined index.

Since strtolower and trim won't make any adjustments to an empty string, you can perform:

$foo = strtolower(trim($_REQUEST['foo'] ?? ''));

Performing your coalesce on the trim parameter will prevent the undefined $_REQUEST index from being evaluated by the trim function.

Upvotes: 2

Related Questions