Do you know a good PHP hack to do inline conditional binding?

I really like the || operator in javascript where we can do standard conditional binding.

 var a = 0; var b = 42; var test = a || b || 'default value'; console.log(test); // 42 

This is readable and does not take up too many lines.


In PHP, this boolean operator returns booleans:

 $a = 0; $b = 42; $test = $a || $b || 'default value'; print_r($test); // bool(true) 

Of course, we can do inline binding using tees :

 $test = $a ? $a : $b ? $b : 'default'; print_r($test); // int(42) 

But this makes the code ambiguous; it is not so easy to read.


So here is my question:

Do you know a good PHP hack to do inline conditional binding?

+4
source share
2 answers

In PHP 5.3+, you can do this :

 $test = $a ?: ($b ?: 'default value'); 
+3
source

This will work until you need the side effects of a short circuit:

 function either_or() { $nargs = func_num_args(); if ($nargs == 0) { return false; } $args = func_get_args(); for ($i = 0; $i < $nargs-1; $i++) { if ($args[$i]) { return $args[$i]; } } return $args[$nargs-1]; } $test = either_or($a, $b, "Default value"); 
+1
source

Source: https://habr.com/ru/post/1480317/


All Articles