2
\$\begingroup\$

I have this if else statement where I don't know how to remove the code duplication

if(array_key_exists($key,$cachetable))
{
 if($cachetable[$key] != $newdata[$key])
  {
    //data existed but is not valid
    //update the cachetable
    $cachetable[$key] == $newdata[$key]
  }
}

else
{
    //data didn't existed before in cache so add it now
    //update the cachetable
    $cachetable[$key] == $newdata[$key]
 }
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Modify the code to this:

//just use the AND operator (&&) to check if it's both existing AND valid
//use strict comparison (===) whenever possible
if(array_key_exists($key,$cachetable) && $cachetable[$key] === $newdata[$key]){
    //data exists and valid
} else {
    //data doesn't exist or isn't valid
    //to assign data, use a single equal (=). 
    //A double equal (==) is a loose comparison
    $cachetable[$key] = $newdata[$key];
 }

//this one checks if it's not in the array
//or if it does, it checks if it's not valid
//when either one is true, the condition passes
if(!array_key_exists($key,$cachetable) || $cachetable[$key] !== $newdata[$key]){
    //data doesn't exists or isn't valid
}
\$\endgroup\$
6
  • \$\begingroup\$ I thought of this myself but then thought that I should check $cachetable[$key] === $newdata[$key] only after doing the array_key_exists() otherwise some error would occur. was I wrong? is it possible to check both things in one if statement? \$\endgroup\$
    – nischayn22
    Jun 14, 2012 at 6:56
  • \$\begingroup\$ as far as i know, if a condition fails in an AND (&&), PHP does not continue evaluating the rest of the conditions. therefore, $cachetable[$key] === $newdata[$key] is only evaluated when array_key_exists($key,$cachetable) returns true. \$\endgroup\$
    – Joseph
    Jun 14, 2012 at 6:59
  • 1
    \$\begingroup\$ The && operator is a "short circuit" operator, meaning it only evaluates the expression to the right if the one to the left evaluated to true. \$\endgroup\$ Jun 14, 2012 at 6:59
  • \$\begingroup\$ Ok, However I don't do anything when the data is valid, so maybe you could edit the answer to have only a if with the ! appended there \$\endgroup\$
    – nischayn22
    Jun 14, 2012 at 7:02
  • 1
    \$\begingroup\$ if( ! array_key_exists($key, $cachetable) || $cachetable[$key] !== $newdata[$key]) { } - removes need for else statement \$\endgroup\$
    – mseancole
    Jun 14, 2012 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.