Search code examples
phparrayspdounset

Shorten code for removing array element with conditional in php pdo


Is there a way to shorten this code? It just seems clunky. Ive tried several shorthand ideas with ternary operators and couldnt get anything to work. So this is what I came up with. Any thoughts would be appreciated.

$query = $db->prepare($sql);
$array = array(':page_parent' => $parent_id, ':page_active' => $active);

if(is_null($active)):
    unset($array[':page_active']);
endif;

$query->execute($array);

Solution

  • $query = $db->prepare($sql);
    $array = array(':page_parent' => $parent_id, ':page_active' => $active);
    //array_filter will remove null and false array element 
    $array = array_filter($array);
    $query->execute($array);