NYCPHP Meetup

NYPHP.org

[nycphp-talk] Why doesn't this work: chained ?: expressions

Adam Maccabee Trachtenberg adam at trachtenberg.com
Fri Jan 17 12:46:14 EST 2003


WRT your problems chaining ?: statements, PHP has ** a different
** presidence order than C. This was an accident, but now it's
backwards compatibility. It certainly does lead to a high WTF factor,
however.

-adam

-- 
adam at trachtenberg.com
co-author of o'reilly's php cookbook

On Fri, 17 Jan 2003, David Sklar wrote:

> You don't have to add many parenthesis to get it to work right:
> 
> $output = preg_match ( '/one/i', $input ) ? '01'
>         : (preg_match ( '/two/i', $input ) ? '02'
>         : (preg_match ( '/three/i', $input ) ? '03'
>         : (preg_match ( '/four/i', $input ) ? '04': '00')));
> 
> 
> You could do it with less calls to preg_match() like this:
> 
> $map = array ('one' => '01', 'two' => '02',
>               'three' => '03', 'four' => '04');
> $output = preg_match('/'.join('|',array_keys($map)).'/',$input,$matches)) ?
>           $map[$matches[0]] : '00';
> 
> You might also want to put some anchors around the "one" "two" "three", etc.
> or when $input is "none", $output will be "01".
> 
> -dave
> 
> > -----Original Message-----
> > From: George Webb [mailto:gw.nyphp at gwprogramming.com]
> > Sent: Thursday, January 16, 2003 8:50 PM
> > To: NYPHP Talk
> > Subject: [nycphp-talk] Why doesn't this work: chained ?: expressions
> >
> >
> > Hi PHP Team!
> >
> > 	I'm sure "associativity" is the answer to why doesn't this work
> > as desired, but perhaps someone could suggest how to get this
> > sexy expression
> > chain to work, and still look sexy:
> >
> >
> > -----
> > $input = $argv[1];
> >
> > $output = preg_match ( '/one/i', $input ) ? '01'
> >         : preg_match ( '/two/i', $input ) ? '02'
> >         : preg_match ( '/three/i', $input ) ? '03'
> >         : preg_match ( '/four/i', $input ) ? '04'
> >         : '00';
> >
> > echo "$input => $output\
";
> > -----
> >
> >
> > Here is some sample output:
> >
> > one => 04
> > two => 04
> > three => 04
> > four => 04
> > five => 00
> > asdf => 00





More information about the talk mailing list