Simplify conditionals using arrays in 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
}