Array in comparison syntax... possible?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
batfastad
Forum Contributor
Posts: 433
Joined: Tue Mar 30, 2004 4:24 am
Location: London, UK

Array in comparison syntax... possible?

Post by batfastad »

Hi everyone

Just had a thought... is there a way to compare the result of a function where the result is an array by adding the key number to the end of the function?

Some sort of syntax like this?

Code: Select all

if ($var == explode(',', $string)[1] ) {
The only alternative I can think of is setting the result of explode() to a variable and then doing the compare.
Is there an alternative syntax/way of doing things I'm missing out on?

Cheers, B
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Array in comparison syntax... possible?

Post by requinix »

Nope. Not yet, at least. And no easy alternative that I can think of.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Post by Jonah Bron »

Bummer, isn't it? You can do it in several other languages :(
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: Array in comparison syntax... possible?

Post by Weiry »

tasairis wrote:Nope. Not yet, at least. And no easy alternative that I can think of.
If you really had to compare against the exact key of the array, you could just use this.

Code: Select all

 
if (array_search($var,explode(',', $string)) == 1) { // where 1 is the key your checking against
    print "ok";
}else{
    print "not ok";
}
 
User avatar
batfastad
Forum Contributor
Posts: 433
Joined: Tue Mar 30, 2004 4:24 am
Location: London, UK

Re: Array in comparison syntax... possible?

Post by batfastad »

Yeah fair enough.
As it goes I'll need to do comparison on a couple of other members of the array so it makes sense to explode it to a variable first.

Just thought that adding an array key to the end of a function would be a useful bit of syntax if it existed.

Cheers for the help ;)
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Array in comparison syntax... possible?

Post by jackpf »

I agree. I was thinking this a while ago. Javascript does it!!!
Post Reply