Skip to content

Instantly share code, notes, and snippets.

@agaezcode
Forked from JeffreyWay/set-value.md
Last active May 14, 2024 03:51
Show Gist options
  • Save agaezcode/da2051f73f58405296cb to your computer and use it in GitHub Desktop.
Save agaezcode/da2051f73f58405296cb to your computer and use it in GitHub Desktop.

You know how, in JavaScript, we can set a value to a variable if one doesn't, like this:

name = name || 'joe';

This is quite common and very helpful. Another option is to do:

name || (name = 'joe');

Well, in PHP, that doesn't work. What many do is:

if ( empty($name) ) $name = 'joe';

Which works...but it's a bit verbose. My preference, at least for checking for empty strings, is:

$name = $name ?: 'joe';

What's your preference for setting values if they don't already exist?

@agaezcode
Copy link
Author

php Echo number if number is not a zero.

$number ?: $number != '0'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment