DEV Community

Roy R.
Roy R.

Posted on

4 1

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:

<?php
$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:

<?php
$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).

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay