3

I need to check if the fields in an array are empty. I would like to know if there is any function in PHP that does this. I've tried empty(), but since it checks if the array is empty, it returns false because the array has fields.

The following array is below:

"wm" => array:7 [▼
    "make" => null
    "model" => null
    "version" => null
    "portal_plan_id" => null
    "portal_highlight_id" => null
    "price_type_id" => null
    "announce" => null
  ]

See that the values are null and they are the ones I need to check.

Thank you!

4
  • i'm so sorry, I did not see that I was asking on the wrong website. Commented Jun 22, 2018 at 18:24
  • Do you need to know if every value is null or only specific ones? Commented Jun 22, 2018 at 19:08
  • every value @NMahurin Commented Jun 22, 2018 at 19:59
  • Which field do you want to check? Commented Jun 22, 2018 at 20:18

2 Answers 2

4

There are two ways to do this depending on what you need. If you want to know if any values are null: http://php.net/manual/en/function.array-search.php

array_search(null, $array)

The array_search will return false if no keys are null. So you can do

if(array_search(null, $array) !== false){
    // There is at least one null value
}

If you want to know which keys hold a null value: http://php.net/manual/en/function.array-keys.php

array_keys($array, null)

The array_keys will provide all keys that have a null value. So you can check

if(count(array_keys($array, null)) > 0){
    // There is at least one null value. array_keys($array, null) can retrieve the keys that are null
}
Sign up to request clarification or add additional context in comments.

Comments

0
$array = [
     'make' => KIA,
     'model' => Koup,
     'version' => 5.0,
     'portal_plan_id' => null 
];

if(in_array(null, $array)){
    // do something
}

The above checks if there there is at least one null value, in this case it will evaluate to true

$array = [
   'make' => null,
   'model' => null,
   'version' => null,
   'portal_plan_id' => null  
];

if(count(array_unique($array)) == 1 && array_unique($array)['make'] == null)
{        
       //do something
}

Where ['make'] is your first index, you can pick any index. The above will evaluate to true. This is how it works; it checks if all values are the same(array_unique($array)) == 1) and if the first value is null (array_unique($array)['make'] == null). By logic if the first value is null and all values are the same, you can conclude that all values are null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.