Updating or adding data to an associative array as a cache

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]
}


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
}

• 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? Jun 14, 2012 at 6:56
• 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. Jun 14, 2012 at 6:59
• 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. Jun 14, 2012 at 6:59
• 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 Jun 14, 2012 at 7:02
• if( ! array_key_exists($key,$cachetable) || $cachetable[$key] !== $newdata[$key]) { } - removes need for else statement Jun 14, 2012 at 13:35