Simplify conditionals using arrays using PHP/JS

Last modified May 15, 2021
.* :☆゚

If you write PHP or JS, you may have written an if condition using logical operators like so:

<?php
if ( get_post_type() === 'Projects' || get_post_type() === 'Testimonials') {
  // ...code here
}

This can get pretty messy and arduous to read if you have a lot of variables to check against.

A simple solution to this problem is to check the value against an array of values instead.

In PHP, this might look something like this:

<?php
if ( in_array(get_post_type(), ['Projects','Testimonials']) ) {
  // ...code here
}

In JavaScript, it might look something like this:

if ( ['green-bg','blue-bg'].includes(elem.id) ) {
  // ...code here
}
Jaclyn Tan

I'm Jaclyn and I make websites. I aim to make the web a more fun and accessible place, sharing what I learn along the way.

My blog has no ads or sponsors and I plan on keeping it that way. If you like what I do please consider supporting me.