0
votes

What I'm trying to do:

treat the POST data from a multi-select input with the array_diff() function

Initial code:

$relations_to_delete=array_diff($selectedEnjeuxMetiers,$this->request->data['EnjeuxMembership']['EnjeuxMetier']);

Probem: It was not working when nothing was selected in the multiselect input

Current solution:

  if(!empty($this->request->data['EnjeuxMembership']['EnjeuxMetier'])){
        $relations_to_delete=array_diff($selectedEnjeuxMetiers,$this->request->data['EnjeuxMembership']['EnjeuxMetier']);
                                                         
   }else{
            $relations_to_delete=$selectedEnjeuxMetiers;
   }

This solution works. !=null was not working, nor gettype()=="array"

Question: Could anyone could explain why the if(!empty()) test is necessary, and if the problem comes from the POST data or the array_diff function?

EDIT: It works with gettype()=="array". The problem was that the type when there is no data is not an empty array but an empty string.

Additional info: CakePHP docs about the way Post data are converted to an array.

2
Give a var_dump on the value and tell us the value returnedFabianoLothor
It returns '' So it's an empty string.L. Sanna
Ok solved. It works with gettype()==array. Must have made a typo the first time.L. Sanna
var_dump("" != null) return false the correct is var_dump("" !=== null) about the array, use is_array function.FabianoLothor
Thanks Fabiano. Copy this comment and I will accept.L. Sanna

2 Answers

0
votes

With the function "empty()", the variable is considered empty if it is equal to:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

The value should be coming "" or NULL when no option is selected.

0
votes

The problem was that the type when there is no data is not an empty array but an empty string.