Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a code which needs a variable compare string

array(
        'key' => 'rob_value',
        'value' => $rob,
        'compare' => '='   
     )  

the compare =>'=' needs to be '=' to get values according a variable data from search form, but sometimes the value is null (empty) and the compare line needs to change to compare =>'!='

I have tested changing the code manually and it works perfectly. Now I want to do the code change according the values on search form.

share|improve this question
    
where is problem? –  Alexey Nov 24 '11 at 0:16
    
@Alexey the compare line now is '=',and I need the line changes automatically to '!=' value.... something like if $rob="" then $rob_comp="!=" else $rob_comp="=" then we got to array to use 'compare'=>$rob_comp instead '=' or '!=' only. –  Fernando Baltazar Nov 24 '11 at 0:38
    
Just change it! I don't see a problem. How can I help you? –  Alexey Nov 24 '11 at 1:14
1  
I found the anwser to my last 3 questions the meta_query works perfect! first I need to do this: php if($rob != '') { $rob_comp= '='; } else { $rob_comp= '!='; } then change the code for array array( 'key' => 'rob_value', 'value' => $rob, 'compare' => $rob_comp ) Doing this works for more than 2 meta_query with no need to do a wpdb=>query –  Fernando Baltazar Nov 24 '11 at 1:51
1  
Please add this as an answer and accept it. –  Rutwick Gangurde Nov 24 '11 at 3:43
add comment

1 Answer

Use a ternary operation to keep it trim.

array(
    'key' => 'rob_value', 
    'value' => $rob, 
    'compare' => ( empty( $rob ) ? '!=' : '=' )
);

Breakdown, incase you've not seen ternary operators before..

array(
    'key' => 'rob_value', 
    'value' => $rob, 
    'compare' => ( 
        // If
        empty( $rob ) 
        // Then
        ? '!=' 
        // Else
        : '=' 
    )
);

http://php.net/manual/en/language.operators.comparison.php

FYI: This question should ideally have been on StackOverflow, it's more centric to general PHP(if/else/comparison) than to WordPress(you just happening to be writing code for WordPress).

All the same, hope that helps..

share|improve this answer
    
thanks for this example, I wrote the if operators outside the query to use an extra $string... but this code is easier to follow. This also helps to close this answer, Thanks to all! –  Fernando Baltazar Nov 30 '11 at 7:48
2  
@FernandoBaltazar please come back and accept this answer if it solves your problem. –  Chip Bennett Feb 14 '12 at 17:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.