Oli1
1
I know it’s totally not related to Kirby, but is there a prefered way for if else statements? Example:
$img_cmp_bw = false;
if ( $data->img_cmp_bw()->bool() ) {
$img_cmp_bw = true;
}
or the other method
if ( $data->img_cmp_bw()->bool() ) {
$img_cmp_bw = true;
} else {
$img_cmp_bw = false;
}
The if statement is not really necessary at all in this case:
$img_cmp_bw = $data->img_cmp_bw()->bool();
If field doesn’t exist or is empty or is false it will return false, else true.
For other simple use cases, ternary operators are useful:
$var = $page->test()->isNotEmpty() ? $page->test() : 'fallback';
Here we check if the field is empty, and use the value if not and a fallback if yes.
For this particular case, Kirby has a shorter way of doing this with or()
:
$var = $page->test()->or('fallback');
Or the null coalesce operator:
$username = $_GET['user'] ?? 'nobody';
In this example, the variable is set to $_GET['user']
if it is set and falls back to nobody
if not.
But to answer your question, I’d probably go with the first option, less lines of code;
1 Like
Oli1
3
Amazing explanation!!! Exactly what I was looking for, thanks 