Search code examples
phpwordpressselectnotnull

not null not working with php (wordpress)


I would like to display a tag in wordpress if a variable isn't null. But the executes even if the variable is null. Here are my variables:

<?php
$st_tr = get_field('startkostnad_transfertryck') ?: 'null';

$tr_vo1_f1 = get_field('tr_vo1_f1') ?: 'null';
$tr_vo1_f2 = get_field('tr_vo1_f2') ?: 'null';
$tr_vo1_f3 = get_field('tr_vo1_f3') ?: 'null';
$tr_vo1_f4 = get_field('tr_vo1_f4') ?: 'null';
$tr_vo1_f5 = get_field('tr_vo1_f5') ?: 'null';
$tr_vo1_f6 = get_field('tr_vo1_f6') ?: 'null';
?>

And where it's executed:

<?php    
if ($st_tr) {
    echo $st_tr;    
?>
<select name="print" id="print_m">
    <option value="0">Ingen märkning</option>
    <?php
    // Color quantities   
    $c_q = array("$tr_vo1_f1", "$tr_vo1_f2", "$tr_vo1_f3", "$tr_vo1_f4", "$tr_vo1_f5", "$tr_vo1_f6");
    // not null
    $c_q_nn = array_filter($c_q, 'strlen');

    // Color quantity and display (check if exists)
    if ($tr_vo1_f1){    
       $c_q_d_f1 = "1-färgstryck";  
    }  
    if ($tr_vo1_f2){
       $c_q_d_f2 = "2-färgstryck";  
    }  
    if ($tr_vo1_f3){
       $c_q_d_f3 = "3-färgstryck";  
    }   
    if ($tr_vo1_f4){
       $c_q_d_f4 = "4-färgstryck";  
    }  
    if ($tr_vo1_f5){
       $c_q_d_f5 = "5-färgstryck";  
    }  
    if ($tr_vo1_f6){
       $c_q_d_f6 = "6-färgstryck";  
    }      
    $c_q_d = array("$c_q_d_f1", "$c_q_d_f2", "$c_q_d_f3", "$c_q_d_f4", "$c_q_d_f5", "$c_q_d_f6");
    $c_q_d_nn = array_filter($c_q_d, 'strlen');
    foreach (array_combine($c_q_nn, $c_q_d_nn) as $color_q => $color_q_d) {    
        echo '<option value="' . $color_q . '">' . $color_q_d . '</option>';     
    }

    ?>    
</select>    
<?php 
}
?>

This also executes the last variable $tr_vo1_f6. The if statements seems to be the problem but I can't figure out how to write them differently except if (!($var == NULL)) which from what I've read would be the same as if($var).

How would I write the if statements correctly?


Solution

  • You are assigning a string and not a really null value. You should fix with:

    <?php
    $st_tr = get_field('startkostnad_transfertryck') ?: null;
    
    $tr_vo1_f1 = get_field('tr_vo1_f1') ?: null;
    $tr_vo1_f2 = get_field('tr_vo1_f2') ?: null;
    $tr_vo1_f3 = get_field('tr_vo1_f3') ?: null;
    $tr_vo1_f4 = get_field('tr_vo1_f4') ?: null;
    $tr_vo1_f5 = get_field('tr_vo1_f5') ?: null;
    $tr_vo1_f6 = get_field('tr_vo1_f6') ?: null;
    ?>