-1

Is it just me or is it just odd to have the precedence of assignment be higher than any other operator? Example in PHP I just came across:

    function test($param1) {
        $result = TRUE;
        for ($i = 0; $i <; strlen($param1); $i++) {
            if (!(ord($param1[$i]) >= 65 && ord($param1[$i]) <=90)) {
                $result = $result && FALSE;
            }
        }
        return $result;
    }

The intention when calling this function is to check whether a string has all characters in the range A-Z (If there are better ways it would be great to hear about them). The key part being the $result = $result && FALSE which I had thought would evaluate the right side to FALSE then assign $result that value.

But No. This little bug/feature took some tracking down.

It appears that the the assignment of $result = $result is performed first then to no-one the operation TRUE && FALSE; is carried out. I actually had to give explicit direction to say $result = ($result && FALSE); which does seem very bizarre.

Anyway, I don't see how this is particularly useful 'feature' to have? Any ideas or am I missing something really basic?

mykhamill
  • 13
  • 3

2 Answers2

1

If there are better ways it would be great to hear about them

ctype_upper()

It appears that the assignment is performed first then the && operation

You are mistaken. You are confused by the combination of your (incorrect) test of characters against integers and the reassignment of $result in a tight loop.

As noted in the comments, fail early.

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

characters are not ints in PHP, you need to call ord on them to get meaningful comparison with the number literals.

as far as better ways are concerned, how about preg_match() with ^[A-Z]*$?

so the real problem with your code is that it never enters the innermost if.

Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87
just somebody
  • 18,602
  • 6
  • 51
  • 60
  • Sorted the question regarding the ords. They were in the original code that caused the behaviour. Thanks for the tip on preg_match(). – mykhamill Nov 15 '12 at 20:24
  • if the code you paste here is not the code that you actually use (cut down to the necessary minimum and still exhibiting the unexpected behavior), then you probably won't get meaningful answers here. like, maybe your *real* code has `$result = $result & false` (not the single ampersand)... we'll never know. – just somebody Nov 16 '12 at 11:02