OR inside a conditional statement

Discussion in 'PHP' started by guruguy, May 17, 2008.

  1. #1
    I trying to get the following type of code to work, with little success. How do I get the conditional to kick in only if $j = 3 or 5. At the moment the script is always echoing success.

    
    <?php
    
    $j = 6;
    $primes = 3||5;
    if ($j == $primes)
    {
    echo "success";
    }
    else
    {
    echo "failure";
    }
    ?>
    
    PHP:
    The real use is within a for loop, it's just that I can't work out how to get it going with an or.
     
    guruguy, May 17, 2008 IP
  2. allaboutgeo

    allaboutgeo Peon

    Messages:
    85
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try this code

    <?php

    $j = 6;
    if ($j == 3 || $j == 5)
    {
    echo "success";
    }
    else
    {
    echo "failure";
    }
    ?>
     
    allaboutgeo, May 17, 2008 IP
  3. allaboutgeo

    allaboutgeo Peon

    Messages:
    85
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Or you can use in_array() function
    <?php
    
    $j = 6;
    $primes = array(3,5);
    if (in_array($j, $primes))
    {
    echo "success";
    }
    else
    {
    echo "failure";
    }
    ?>
    Code (php):
     
    allaboutgeo, May 17, 2008 IP
    guruguy likes this.
  4. samyak

    samyak Active Member

    Messages:
    280
    Likes Received:
    7
    Best Answers:
    4
    Trophy Points:
    90
    #4
    using in_array is a better solution, becuase with this code you can expand your list of prime numbers simply by adding new numbers in the array.
     
    samyak, May 19, 2008 IP
  5. guruguy

    guruguy Active Member

    Messages:
    553
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    60
    #5
    I have used the in_array function due to it being easier to use and easier to expand upon. Thanks for the idea
     
    guruguy, May 29, 2008 IP
  6. allaboutgeo

    allaboutgeo Peon

    Messages:
    85
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #6
    You are welcome!
     
    allaboutgeo, Jun 1, 2008 IP