0

Is there a way to optimize something like this?
I have already tried and it doesn't work (at least in php)

$foo = 6;
if ($foo != (3 or 5 or 10)) echo "it work";
elseif($foo < (5 or 10)) echo "it work again";
else echo "it doesn't work;"

I want to know if there's a better way to write that kind of validations.
But if something like this work in other langs, please let me know.


EDIT:
answer for this

($foo != (3 or 5 or 10)) -> in_array($foo,array(3,5,10))


does the same work if i want something like

($foo != (3 and 5 and 10)) 

3 Answers 3

3

No. It's not. You're testing your $foo value against the BOOLEAN result of those or operations. It'll boil down to

if ($foo != (true or true or true))

which is simply

if ($foo != true)
if (!$foo)

If you want to test a single value against multiple values, you can try

if(!in_array($foo, array(3,5,10))) { ... }

instead. For your < version, this won't work. You'll have to test each value individually:

if (($foo < 5) or ($foo < 10)) { ... }

though technically this is somewhat redundant, since if $foo is less than 5, it's already less than 10.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is an excellent answer but I think the real issue that needs to be addressed is the fact that micro-optimization is 99% not worth the effort and makes code illegible for future reading.
0

For the first you can use

if(!in_array($foo, [5,10,15]))

The second thing doesn't work in any language cause less then 5 or 10 is true for every thing less than 10. So no need for the 5. But I get your point. I don't know a fast way doing this

In python you can do this:

if(5 < x < 10)
    a, b = b, a // swapping these two

Comments

0

I agree with the other answers and also, if you have more processing to do, you could also do something like this:

<?php

$x = 3;

switch ($x)
{
    case 6:
        $x = 5;
    case 3:
    case 7:
        $x = 5;
    case 5:
        echo 'It is working' . PHP_EOL;
        break;
}

EDIT: Thanks DanFromGermany for pointing the stacked cases. Added them as an example.

5 Comments

You forgot the break;s
No, I did not. Why would you exit the loop before doing your job?
No need for breaks if you don't want them!
or stack the cases: case 6: case 3: $x = 5;
@FlorinAsavoaie - without the break; the first and second cases will both run if $x == 6. In this case, it doesn't matter because they do the same thing, but can be a dangerous mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.