I'm looking for effective implementation of Material Implication/XNp/If/then for PHP. Here's example of where I want to use it:
There is collection of object. Each of them has date and type.
I'm writing method that accepts three parameters:
function isNewest($obj, $collection, $sameTypeOnly = true){}
and check if the $obj
has newer date (bigger timestamp) than any of objects in $collection
. I also want to depend my comparison on $sameTypeOnly
which narrows comparations only to objects of same type.
So far I have:
$currentDate = strtotime($obj->getDate());
foreach($relatedObjects as $related){
if($currentDate < strtotime($related->getDate()) && >>SOMETHING<<){
return false;
}
}
return true;
There is problem with SOMETHING
. I want it to check if $sameTypeOnly
is true, and if it is, check if $obj->getType() == $related->getType()
.
Of course, I could do that using nested if()
statements like this:
$currentDate = strtotime($obj->getDate());
foreach($relatedObjects as $related){
if($sameTypeOnly){
if($obj->getType() == $related->getType() && $currentDate < strtotime($related->getDate()){
return false;
}
} else {
if($currentDate < strtotime($related->getDate()){
return false;
}
}
}
return true;
and it will work! BUT IT LOOKS BAD. I wonder if there is simplier, effective and elegant solution to do this in one if.
After minute of thinking I got my truth table. Assuming that T
stands for same type
, t1 = t2
means that type of first objects matches type of second objects, and r
is result
, truth table looks like this:
T | t1 = t2 | r
---|---------|----
T | T | T
---|---------|----
T | F | F
---|---------|----
F | T | T
---|---------|----
F | F | T
I looked up for similar table here, and well, here it is! Column 11 on this table (named "if/then"). I googled for PHP implementation of this operation, with no luck.
Is there any way to implement it using only operators available in PHP? Will it be efficient and fast?