$sql_id_str=""; $num_iids=count($iid); if ( $num_iids === 1 ) { foreach ($iid as $id) { $sql_id_str.=" iid=". $id; } $sql_inst="select instance_key from instances where eid=" . $eid . " and rcid=". $rcid . " and " . $sql_id_str; } else { $i=0; foreach ( $iid as $id ) { $sql_id_str.=" iid=". $id; $i++; if ( $i === $num_iids ){ $sql_id_str.=" "; } else { $sql_id_str.=" or "; } $sql_inst="select instance_key from instances where eid=" . $eid . " and rcid=". $rcid . " and (" . $sql_id_str . ")"; } } echo $sql_inst;