0

I have two arrays $a and $b, the first being the data used to populate a form, the other being the output of the form, which may have been changed by the user. We cannot assume that all inputs are present in both arrays. I want a new array which contains only those inputs which are not NULL and which have been changed by the user.

The truth table for this looks to me like

isset($a)      isset($b)      output
   N              N           NULL
   N              Y           $b
   Y              N           empty string
   Y              Y           ($a != $b ? $b : NULL)

Trying to convert this to PHP code, I've derived this horrible compound ternary thing for each member mem of the array (assumed scalar):

$changedData = 
    (isset($a[mem]) 
    ? 
        (isset($b[mem]) 
        ? 
            ($a[mem] != $b[mem] ? $b[mem] : NULL) 
        : 
            '')
     : 
     (isset($b[mem]) ? $b[mem] : NULL)
);

There must surely be a better way of doing this. Your advice will be greatly appreciated.

rbr94
  • 2,227
  • 3
  • 23
  • 39
magnol
  • 344
  • 3
  • 15
  • 1
    Shouldn't `array_filter` help you in this case? After all, this looks like a pretty good exercise to learn test driven development, as you could simply write down test cases for each different input array to nail down the neccessary algorithm – Nico Haase Jan 13 '20 at 09:25
  • Why don't you just use a table? It's a two-dimensional dictionary (`array` in PHP) mapping between boolean values and some mixed output values. – Ulrich Eckhardt Jan 13 '20 at 09:25
  • @UlrichEckhardt: I've never encountered dictionaries. Could you enlarge on how to implement one in PHP? – magnol Jan 13 '20 at 10:44
  • @NicoHaase: Clearly I have some learning to do! Thanks for pointing me to this. – magnol Jan 13 '20 at 10:46
  • The PHP `array` is both a sparse array or list (a sequence of elements with numeric index) and a dictionary (key/value mapping). Simple example would be `['fou' => ['barre' => 'baz']]`. – Ulrich Eckhardt Jan 13 '20 at 14:12

0 Answers0