Archive for December, 2011

Testing multiple conditions in if statements

Friday, December 2nd, 2011 | Programming

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.

Mark Edon tells it like it is

Thursday, December 1st, 2011 | Events, Humanism

Mark Edon recently gave a talk to West Yorkshire Humanists about “talking to creationists.” I’ve already seen Mark talk three times before but never the less it was interesting as ever, with plenty of fresh material.