DEV Community

Roy Ronalds
Roy Ronalds

Posted on

Short circuit expressions in php?

I enjoy using short circuit evaluation in javascript. Since I work with a legacy php personal project, I would like to write simpler, terser and easier code in php as well. So what is the equivalent of js short circuit expressions in php?

For example, in js you can write:

const complexEvaluated = someEvaluation() && false // false
const finalCount = complexEvaluated || 0 // zero
Enter fullscreen mode Exit fullscreen mode

It's great to be able to quickly create fallbacks and immediately and visibly ensure that a variable has a value.

In php, short circuit fallthrough doesn't work exactly the same way:

$complexEvaluated = someEvaluation() || 7; // boolean true
$finalCount = countUp() || 0; // boolean true
Enter fullscreen mode Exit fullscreen mode

Instead it is necessary to use null coalescing, usually:

$complexEvaluated = someEvaluation() ?? 7; // 7
$complexEvaluated = someEvaluationToFalseOrZero() ?: 44; // 44
$finalCount = countUp() ?? 0; // 0
Enter fullscreen mode Exit fullscreen mode

And you essentially have to use a different operator for falsy outcomes vs null outcomes, the short ternary ?: vs the null coallescing operator ??

In another post I will cover the equivalent of js destructuring in php, or as close as you can get (spoiler: It's useful, but not as useful as js destructuring).

Top comments (0)