How to check if an array has at least one non-empty value in php, WordPress?

To check if there is at least one non-empty value in an array in PHP, including scenarios using WordPress, you can use the following methods:

Method 1: Using array_filter

The array_filter function removes all empty values from an array and returns a new array. If the filtered array is not empty, it means that there was at least one non-empty value in the original array.

$array = ['value1', '', null, 'value2', 0];

if (!empty(array_filter($array))) {
    echo 'The array contains at least one non-empty value.';
} else {
    echo 'All values in the array are empty.';
}

Method 2: Using foreach Loop

If you need to consider only specific types of non-empty values, you can use a foreach loop and check the values manually:

$array = ['value1', '', null, 'value2', 0];

$hasValue = false;

foreach ($array as $value) {
    if (!empty($value)) {
        $hasValue = true;
        break;
    }
}

if ($hasValue) {
    echo 'The array contains at least one non-empty value.';
} else {
    echo 'All values in the array are empty.';
}

Method 3: Using array_map and in_array

If you need to check for the presence of at least one specific value (for example, a non-empty string), you can use array_map and in_array.

$array = ['value1', '', null, 'value2', 0];

// Apply a function to each element of the array
$mappedArray = array_map(function ($value) {
    return !empty($value) && $value !== 0;
}, $array);

if (in_array(true, $mappedArray, true)) {
    echo 'The array contains at least one non-empty value that is not equal to 0.';
} else {
    echo 'All values in the array are empty or equal to 0.';
}

Specifics in WordPress

If you are working with arrays returned by WordPress functions (e.g., meta fields, options, etc.), you can use these same methods. However, note that in some cases, the values may be empty strings or null if the data is not yet set.

By using these approaches, you can check for the presence of at least one non-empty value in any array.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to exclude posts with parent post in wp_query, WordPress

To exclude posts that have a parent (i.e., child posts) in a WP_Query request, you can use the post_parent argument. This argument controls whether the post has a parent or not. To exclude child posts, set the condition post_parent => 0, which means that only top-level posts (posts without a parent) will be included in…
Read more