Refactoring a loop with many boolean conditions I usually spent more time on refactoring than in developing itself. But this little piece of code is really hard to refactor. I'd like to keep it as short as possible, but it's quite undarstandable:

foreach($all_headers as $uid =&gt; $h) // Intera gli headers
{

    // Is the header valid?
    $isInbox   = $h-&gt;to == $mailbox-&gt;address;
    $hasPin    = ($pin = substr($h-&gt;subject, 0, 5)) !== false &amp;&amp; is_numeric($pin);
    $hasTitle  = strlen($title = trim(substr($h-&gt;subject, 5))) &gt; 0;
    $isAllowed = $hasPin &amp;&amp; call_user_func($pincall, $mailbox-&gt;address, $h-&gt;from, $pin);

    $log-&gt;info("messaggio $uid: in:$isInbox pin:$hasPin alw:$isAllowed");

    // Skip this header if not vlaid
    if (!$isInbox || !$hasPin || !$isAllowed) continue;

    // Add some properties to current header
    $h-&gt;title = $hasTitle ? $title : null;
    $h-&gt;pin   = $pin;
    $valid_headers[$uid] = $h;

}


Since i'm filtering $all_headers array, one cool idea would be using array_filter with some kind of mechanism to add/remove conditions "on the fly".

Thank you people, as always.
This won't make it shorter, but you might consider changing the condition checking to only do the actual check if needed instead of doing all of them at once, making you loose the advantage of the short-circuiting || operator.

E.g.

if (!isInbox()) continue;
if (!hasPing()) continue;
...




Another possibility, that is even less short, is to create a filtering iterator, e.g.:

class ValidHeaderIterator extends FilterIterator 
{
    private $mailbox;
    private $pincall;   

    public function __construct($headers, $mailbox, $pincall)
    {
        $this-&gt;mailbox = $mailbox;
        $this-&gt;pincall = $pincall;
        parent::__construct(new ArrayIterator($headers));
    }

    public function accept()
    {
        $header = $this-&gt;getInnerIterator()-&gt;current();
        return isInbox($header) &amp;&amp; hasPin($header) &amp;&amp; isAllowed($header);
    }

    public function isInbox($header)
    {
        return $header-&gt;to == $this-&gt;mailbox-&gt;address;
    }

    public function hasPin($header)
    {
        $pin = $this-&gt;getPin($header);
        return $pin !== false &amp;&amp; is_numeric($pin);
    }

    public function getPin($header)
    {
        return substr($header-&gt;subject, 0, 5));
    }

    public function isAllowed($header)
    {
        return call_user_func($this-&gt;pincall,
                              $this-&gt;mailbox-&gt;address,
                              $header-&gt;from,
                              $this-&gt;getPin());
    }
}


The calling code would then look like:    

foreach(new ValidHeaderIterator($headers, $mailbox, $pincall) as $header) {
    // do stuff
}