Home > Software design >  Wordpress ACF plugin how to get only not empty values
Wordpress ACF plugin how to get only not empty values

Time:05-09

I have group of fields for every post. Not all fields per post has values. I try to get array with all fields and get empty values. How to get only not empty values?

My code:

$parthers_shops_prices = array(
        get_field( 'price_1', $product_id ),
        get_field( 'price_2', $product_id ),
        get_field( 'price_3', $product_id ),
        get_field( 'price_4', $product_id ),
        get_field( 'price_5', $product_id ),
        get_field( 'price_6', $product_id ),
        get_field( 'price_7', $product_id ),
        get_field( 'price_8', $product_id ),
    );

And I get: Array ( [0] => 199 [1] => [2] => [3] => 299 [4] => [5] => [6] => [7] => ).

What I want to get: Array ( [0] => 199 [1] => 299 ).

CodePudding user response:

After loading your values, this additional line should give you the result you want:

$parthers_shops_prices = array_filter($parthers_shops_prices);

This should output

Array ( [0] => 199 [3] => 299 )

If you need to additionally reindex your array, you can then do

$parthers_shops_prices = array_values($parthers_shops_prices);

This should instead output

Array ( [0] => 199 [1] => 299 )
  • Related