Home > Mobile >  How can I prevent my function from treating "0" as empty?
How can I prevent my function from treating "0" as empty?

Time:02-08

I have a lottery search form which concatenate six input fields into a single value and returns the ticket results based on the position. My form works correctly for numbers 1-9, but it is unable to display results when I search for 0.

I believe this is because within my get_numbers() function, the value of '0' is being treated as empty: https://www.php.net/manual/en/function.empty.php

How can I fix my if else statement to stop it treating 0 as empty?

    add_filter('wp_ajax_nopriv_get_numbers', 'get_numbers', 10);
add_filter('wp_ajax_get_numbers', 'get_numbers', 10);

function get_numbers(){
    $str = '';
    if(!empty($_POST['n_1'])){
        $str .= $_POST['n_1'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_2'])){
        $str .= $_POST['n_2'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_3'])){
        $str .= $_POST['n_3'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_4'])){
        $str .= $_POST['n_4'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_5'])){
        $str .= $_POST['n_5'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_6'])){
        $str .= $_POST['n_6'];
    }else{
        $str .= '.';
    }

    $atts = array(
        'numberposts'   => -1,
        'posts_per_page' => -1,
        'post_type'     => 'product',
        'meta_query'    => array(
            array(
                'key'       => 'product_overlay_text',
                'value'     => $str,
                'compare'   => 'REGEXP',
            ),
        ),
    );
    $the_query = new WP_Query( $atts );

    ob_start();
    if($the_query->have_posts()) :
        woocommerce_product_loop_start();
        while($the_query->have_posts()) : $the_query->the_post();
            wc_get_template_part( 'content', 'product' );
        endwhile;
        woocommerce_product_loop_end();
        $content['tickets_data'] = ob_get_clean();
    else:
        $content['tickets_data'] = 'เลขที่ท่านต้องการไม่มีในแผง';
    endif;

CodePudding user response:

You're correct that empty() returns TRUE for 0.

You could instead use filter_input() with the FILTER_VALIDATE_INT filter applied.

You could even simplify the whole thing with a range map...

$str = implode("", array_map(function($i) {
    $val = filter_input(
        INPUT_POST,
        "n_$i",
        FILTER_VALIDATE_INT
    );

    return $val === null || $val === false
        ? '.'
        : $val;
}, range(1, 6)));
  •  Tags:  
  • Related