Testing multiple conditions in if statements

This is one of the geeks among you. I’m currently working on a new open source project which uses a series of database models derived from a base model which includes some standard methods and I was having one problem in particular to do with updating data values in an object.

if (
    !$object->setName($d["name"]) ||
    !$object->setSlug($d["slug"]) ||
    !$object->setDateByArray($d["date"]) ||
    !$object->setContent($d["content"])
) {
    $this->setMessage($object->getMessage());
    return false;
}

As you can see, this does an if statement and then runs all the updates – the idea being that if any of them come back as false, it can set the error message and return false to the controller.

This worked as expected but with one problem – as soon as one of them appears false, PHP stops looking at the other conditions in the if statement. This is a problem because it means the user only gets one piece of feedback at a time. Whereas, it would be much better if we could give them all the fields that were wrong at once.

However, this doesn’t seem possible in the above implementation. Even if I switched it round to check that everything is true, and everything must be true, that suffers from the same problem that once something isn’t, PHP will stop checking the conditions.

I considered whether I could implement it using exceptions – putting all the checks inside a try block and then have the update operations throw an exception if they were invalid. I could then catch this exception and add the error to the list of errors. However, this suffers from the same problem – as soon as the first invalid value triggers an exception, the rest of the try block is ignored.

The solution I have eventually come to is this:

$writes = array (
    $object->setName($d["name"]),
    $object->setSlug($d["slug"]),
    $object->setDateByArray($d["date"]),
    $object->setContent($d["content"])
);

if (in_array(false, $writes)) {
    $this->setMessage($object->getMessage());
    return false;
}

All the operations are run, and their values are fed into an array. That way all the checks get run no matter what value they return. I then search the array for any values set to false and if any of them were, I know there has been a error and can flag it up with the user.

Timeline

Newsletter

Don't have time to check my blog? Get a weekly email with all the new posts. This is my personal blog, so obviously it is 100% spam free.

Metadata

Tags: , , ,

This entry was posted on Friday, December 2nd, 2011 at 12:09 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.