Page 1 of 1

PHP

Posted: July 26th, 2009, 5:21 pm
by DOSGuy
I'm primarily a Pascal/Delphi programmer, and sometimes I'm not able to find the PHP equivalents to programming techniques that I'm used to.

I'm PHPizing the code for convenience (this isn't how you would actually code it in Delphi). In Delphi I could make a statement like:

Code: Select all

if ($animal IN ['cat', 'dog', 'mouse'])
to avoid having to type

Code: Select all

if (($animal == 'cat') OR ($animal == 'dog') OR ($animal == 'mouse'))
or

Code: Select all

if ($number IN [1,2,5,7..10])
to avoid having to type

Code: Select all

if (($number <= 2) OR ($number == 5) OR ($number >= 7))
Is there a PHP equivalent of Delphi's powerful "IN" statement? I can't just type

Code: Select all

if ($animal == 'cat' OR 'dog' OR 'mouse')
because it will always return TRUE. I'd prefer not to use a switch case statement in this situation.

Re: PHP

Posted: July 27th, 2009, 1:59 am
by Qbix

Re: PHP

Posted: July 27th, 2009, 10:33 pm
by DOSGuy
I had a feeling that it was going to be a matter of searching an array. That's still not quite as convenient as 'IN' because I have to waste time defining an array, but I guess this is how it has to be done in PHP. Thank you very much, Qbix.

Re: PHP

Posted: July 28th, 2009, 2:03 am
by Qbix
well I am no PHP expert, but this is how I did it in one of my things.

Re: PHP

Posted: November 10th, 2011, 2:35 pm
by deathshadow
My advice is to use switch/case -- which will actually run fastest of them too. This is true in Pascal as well -- string sets are slow! (numerics aren't much better!).

switch ($animal) {
case 'cat':
case 'dog':
case 'mouse':
// do whatever it is yer doing here
}

case conditions fall through to each-other, so the above is the same as doing a bunch of ||

Oh, and in PHP don't use OR, it's logic is not what you think it is, stick to || -- trust me on this. The first time you hit up against "false or true = false, false || true = true" you'll be ripping your hair out... OR doesn't work like it does in pascal, as it will short circuit eval the first false.

You can also pass arrays as constants since PHP is an untyped language...

if (in_array($animal,['cat','dog','mouse'])) {

Would work too... though dog slow.

Not to bump a three year old post -- just bored :D