Use PHP’s in_array() to compare a variable to multiple values

When comparing a variable with multiple values consider using in_array(), instead of complex if expressions.

I love clean, easy-to-read code, which is why I am not a fan of if statements with complex expressions. For example, consider the following snippet, which is checking a variable against several values:

if ($test_variable === 'value1' || $test_variable === 'value2' || $test_variable === 'value3' || $test_variable === 'value4') {
    // do something if $test_variable is equal to one of the strings

This is not nice and certainly doesn’t feel very DRY.

Using in_array() as the Conditional

Now consider the following code fragment, this time using the in_array function as the if statement’s conditional expression:

if (in_array($test_variable, ['value1', 'value2', 'value3', 'value4']) {
    // do something if $test_variable is equal to one of the strings in the array

In my opinion this is a much cleaner solution that’s easier to read, especially if the code is maintained by a team of developers, where it’s possible the programmer that wrote the code will not be the one maintaining it.

It could be taken a step further by first storing the array in a variable, then using it as the argument, as follows:

$test_array = [
if (in_array($test_variable, $test_array) {
    // do something if $test_variable is equal to one of the strings in $test_array

This approach is very clean and extremely easy to read, especially if the array’s items become more complex in themselves.

Other Approaches

Using in_array is just one way to improve the readability of code, another is the switch() statement, which would handle the if statement’s complexities. Here’s one way to write the code fragment using a switch:

switch ($test_variable) {
    case 'value1':
    case 'value2':
    case 'value3':
    case 'value4':
        $value_exists = true;
        $value_exists = false;

if ($value_exists) {
    // do something if $value_exists is true

But, my personal preference is to use in_array, as it feels cleaner.

Wrapping up

If you think you’re codebase is in need of refactoring, for improved readability (and performance), please get in touch and we’ll gladly help. We have many years of programming experience, in a wide range of languages, including PHP, Java, JavaScript, and (S)CSS. We also specialise in WordPress development, developing custom themes and plugins, and helping clients with all manner of performance, including search engine optimisations.