1

I am calling API through postman and passing following parameters.

reason: string
staff_ids[]:

When pass staff_ids blank then I got [null] in server-side.

so that the condition gets always true.

if(isset($request->staff_ids) && !empty($request->staff_ids)){
//
}

Is there any way to check if array has [null]?

Koala Yeung
  • 7,475
  • 3
  • 30
  • 50
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51

3 Answers3

1

Instead of checking, you may simply filter out all NULL values before other works

if (!isset($request->staff_ids) || $request->staff_ids === null) {
  $request->staff_ids = array(); // default to empty array if is not set or is null
} 

if (!empty($request->staff_ids)) {
  $request->staff_ids = array_filter($request->staff_ids, function ($id) {
    return ($id !== null);
  });

  if (!empty($request->staff_ids)) {
    // ...
  }
}
Koala Yeung
  • 7,475
  • 3
  • 30
  • 50
1

I have filtered array values before checking as @KoalaYeung Answered. It is working fine.

$request->staff_ids = array_filter($request->staff_ids, function ($id) {
        return ($id !== null);
      });

    if(isset($request->staff_ids) && !empty($request->staff_ids)){
      ///

    }

Is there any better approach?

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
  • It depends on which level are you planning to fix. Do you want Postman to not send that `[NULL]` array in the first place? Or do you think is your server side script that generates the `[NULL]` array? Or do you simply want to sanitize your input? – Koala Yeung Sep 30 '19 at 09:11
  • You' re not showing enough of your code to allow deeper diagnosis. – Koala Yeung Sep 30 '19 at 09:12
  • Simply I want to sanitize your input. – Gufran Hasan Sep 30 '19 at 09:32
0

you can check this with is_null function and sizeof() for array

if(!is_null($request->staff_ids) && sizeof($request->staff_ids)){
}
Sepideh
  • 133
  • 1
  • 1
  • 11