NYCPHP Meetup

NYPHP.org

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

David Sklar sklar at sklar.com
Fri Jan 17 11:50:55 EST 2003


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
>
> 	Obviously this is not the desired result.  Must we fix this
> with parentheses, and if so how?  Will it become ugly?  Should I just
> use a bunch of "if" statements?
>
> 	Thanks for your thoughts!
>
>
> Best, George.
>
> George Webb
> gw.nyphp at gwprogramming.com
> (802) 283-4352
>
>
> --- Unsubscribe at http://nyphp.org/list/ ---
>




More information about the talk mailing list