-1

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);
rprincejr
  • 67
  • 1
  • 8
  • You could use `$array= array_filter($array);` to remove empty values from your array – Rizier123 Feb 12 '15 at 13:37
  • @ Whoever down voted my question: Why would someone vote down my question? It wasnt answered on another post here at Stackoverflow. The whole point of this site is to get answers to questions. I didnt ask for someone to do my work for me. If I knew the answer, I wouldnt have asked. If you dont want to help, then dont. And Im sure theres plenty of things you dont know that seem petty or simple to others. Pfft. What a jerk. – rprincejr Feb 12 '15 at 15:17

2 Answers2

0
$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);
Prashant M Bhavsar
  • 1,136
  • 9
  • 13
  • I never used arrays much in php until I started heavy into PDO. So the array_filter function wasnt something that came to mind. Thanks for help! – rprincejr Feb 12 '15 at 14:05
0

Why can't you check before adding it to the array?

$query = $db->prepare($sql);
$array = array(':page_parent' => $parent_id);
if( ! is_null($active))
{
    $array[':page_active'] = $active;
}
$query->execute($array);

Whilst it's the same number of lines, it's more efficient as it only deals with active if it's got something in it, rather than adding it and then removing it if there's nothing in it.

Styphon
  • 10,304
  • 9
  • 52
  • 86