Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jan 2009
    Posts
    160
    Thanks
    40
    Thanked 1 Time in 1 Post

    Question Better way to write this if statement

    Is there a better way to write this? It doesn't seem to work when I dont keep rewriting current_category_id but im sure there is a better way...

    Code:
    if ($current_category_id == 48 || $current_category_id == 52 || $current_category_id == 32)

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,500
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    What you typed is correct ... and the only way it will work.

    If you have a lot of possible values, you would compare the variable to an array of possible values ... like this:
    PHP Code:
    <?php

    // set a value for testing it out.
    $current_category_id=32;

    // here is a list of possible values that make it "true"
    $possible=array(48,52,32,10,77,98,37,22,12);
    $flag=0;
    foreach(
    $possible as $value){
       if(
    $current_category_id == $value){
       
    $flag=1;
       }
    }

    // 0=false ... 1=true
    echo $flag;
    ?>

    in this example, the value is 1 (true).



    .
    Last edited by mlseim; 11-30-2010 at 01:05 AM.

  • Users who have thanked mlseim for this post:

    sackstein (11-30-2010)

  • #3
    Senior Coder
    Join Date
    Jul 2009
    Location
    South Yorkshire, England
    Posts
    2,318
    Thanks
    6
    Thanked 304 Times in 303 Posts
    There's the in_array method too, which makes it just a tad simpler.

    Code:
    <?php
    
    // set a value for testing it out.
    $current_category_id=32;
    
    // here is a list of possible values that make it "true"
    $possible=array(48,52,32,10,77,98,37,22,12);
    
    if (in_array($current_category_id, $possible))
    {
    }

  • Users who have thanked MattF for this post:

    sackstein (11-30-2010)

  • #4
    Regular Coder
    Join Date
    Jan 2009
    Posts
    160
    Thanks
    40
    Thanked 1 Time in 1 Post
    Thanks guys. Its only for 4 values right now but i was curious what I would do in the future if I needed more. That makes sense.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •