PHP

Discuss coding, porting and creating games
Post Reply
User avatar
DOSGuy
Website Administrator
Posts: 1063
Joined: September 2nd, 2005, 8:28 pm
Contact:

PHP

Post 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.
Today entirely the maniac there is no excuse with the article.
User avatar
Qbix
DOSBox Programmer
Posts: 45
Joined: October 31st, 2007, 7:43 am

Re: PHP

Post by Qbix »

User avatar
DOSGuy
Website Administrator
Posts: 1063
Joined: September 2nd, 2005, 8:28 pm
Contact:

Re: PHP

Post 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.
Today entirely the maniac there is no excuse with the article.
User avatar
Qbix
DOSBox Programmer
Posts: 45
Joined: October 31st, 2007, 7:43 am

Re: PHP

Post by Qbix »

well I am no PHP expert, but this is how I did it in one of my things.
User avatar
deathshadow
Classic Game Author
Posts: 35
Joined: February 8th, 2011, 5:42 pm

Re: PHP

Post 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
If everyone is thinking the same, somebody isn't thinking.
Post Reply